androidapp开发入门 androidapp开发教程( 二 )


下面创建Repository(数据仓库)
class WeatherRepository {companion object{fun getWeather(district_id: String, data_type: String, ak: String): Flow<WeatherModel> =flow {var weather = WeatherApiClient.weatherApiService.getWeatherData(district_id,data_type,ak)emit(weather)}.flowOn(Dispatchers.IO)}}下面创建ViewModel
class WeatherViewModel: ViewModel() {val weatherData: MutableState<WeatherState> = mutableStateOf(WeatherState.Empty)init {getWeatherData("110100","all","m5ABoErD6VuCKdyGfqoEjflYvSmn1XqR");}fun getWeatherData(district_id: String, data_type: String, ak: String){viewModelScope.launch {WeatherRepository.getWeather(district_id,data_type,ak).onStart {weatherData.value = https://www.juguize.com/b/WeatherState.Loading}.catch { e ->weatherData.value = WeatherState.Failure(e)}.collect { response ->weatherData.value = WeatherState.Success(response)}}}}在创建ViewModel之前,需要创建Model的状态类
sealed class WeatherState {class Success(val weather: WeatherModel) : WeatherState()class Failure(val error: Throwable) : WeatherState()object Loading : WeatherState()object Empty : WeatherState()}创建好之后,我们在Activity中使用ViewModel
class MainActivity : ComponentActivity() {private val weatherViewModel: WeatherViewModel by viewModels()@ExperimentalMaterialApioverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {WeatherAppTheme {Surface(color = MaterialTheme.colors.background) {setWeather(weatherViewModel = weatherViewModel)}}}}}添加数据请求的状态,如下图:

androidapp开发入门  androidapp开发教程

文章插图
@ExperimentalMaterialApi@Composablefun setWeather(weatherViewModel: WeatherViewModel) {when (val result = weatherViewModel.weatherData.value) {is WeatherState.Success -> {Log.d("--result--",result.weather.toString())}is WeatherState.Failure -> {Text(text = "${result.error}")}is WeatherState.Loading -> {Column(horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier.fillMaxSize().background(brush = Brush.verticalGradient(colors = listOf(color1,color2)))) {Surface(onClick = { },modifier = Modifier.fillMaxWidth(0.6f),color = Color.Transparent) {Row(modifier = Modifier.padding(12.dp),verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.Center) {CircularProgressIndicator(modifier = Modifier.height(16.dp).width(16.dp),strokeWidth = 2.dp,color = Color.White)Spacer(modifier = Modifier.width(10.dp))ComposeText(text = "加载天气数据中...", textColor = Color.White, fontSize = 16.sp)}}}}WeatherState.Empty -> {}}}在上面的代码中,我们添加Loading,状态的UI 。
下面在WeatherState.Success状态下,对UI界面赋值 。
Column(horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier.fillMaxSize().background(brush = Brush.verticalGradient(colors = listOf(color1,color2)))) {Spacer(modifier = Modifier.height(20.dp))LocationScreen(result.weather.result.location)Spacer(modifier = Modifier.height(40.dp))NowScreen(result.weather.result.now)Spacer(modifier = Modifier.height(20.dp))WeatherDaysScreen(result.weather.result.forecasts)}设置定位信息@Composablefun LocationScreen(location: WeatherModel.Result.Location) {ComposeText(text = "${location.city},${location.name}",fontSize = 30.sp)}2.设置当天天气信息
@Composablefun NowScreen(now: WeatherModel.Result.Now) {Column(horizontalAlignment = Alignment.CenterHorizontally) {val img_url = when (now.text) {"阴" -> "http://www.moji.com/templets/mojichina/images/weather/weather/w2.png""雷阵雨" -> "http://www.moji.com/templets/mojichina/images/weather/weather/w4.png""多云" -> "http://www.moji.com/templets/mojichina/images/weather/weather/w1.png"else -> "http://www.moji.com/templets/mojichina/images/weather/weather/w1.png"}Image(painter = rememberImagePainter(img_url),contentDescription = "",modifier = Modifier.size(100.dp))ComposeText(text = "${now.temp}°", fontSize = 48.sp)}Surface(modifier = Modifier.fillMaxWidth(0.5f),color = color3,shape = RoundedCornerShape(48)) {Row(horizontalArrangement = Arrangement.SpaceBetween,verticalAlignment = Alignment.CenterVertically,modifier = Modifier.fillMaxWidth().padding(8.dp)) {ComposeText(text = "${now.windDir}", textColor = colortext, fontSize = 12.sp)ComposeText(text = "${now.windClass}", textColor = colortext, fontSize = 12.sp)ComposeText(text = "湿度", textColor = colortext, fontSize = 12.sp)ComposeText(text = "${now.rh}%", textColor = colortext, fontSize = 12.sp)}}}3.设置未来5天的天气信息
@Composablefun WeatherDaysScreen(forecasts: List<WeatherModel.Result.Forecast>) {LazyRow {items(forecasts){ forecast ->WeatherItems(forecast)}}}@Composablefun WeatherItems(forecast: WeatherModel.Result.Forecast) {Column(horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier.padding(start = 8.dp,end = 10.dp)) {ComposeText(text = "${forecast.week}",fontSize = 16.sp)Spacer(modifier = Modifier.height(18.dp))val img_url = when (forecast.textDay) {"阴" -> "http://www.moji.com/templets/mojichina/images/weather/weather/w2.png""雷阵雨" -> "http://www.moji.com/templets/mojichina/images/weather/weather/w4.png""多云" -> "http://www.moji.com/templets/mojichina/images/weather/weather/w1.png"else -> "http://www.moji.com/templets/mojichina/images/weather/weather/w1.png"}Image(painter = rememberImagePainter(img_url),contentDescription = "",modifier = Modifier.size(50.dp))Spacer(modifier = Modifier.height(2.dp))ComposeText(text = "${forecast.high}°/${forecast.low}°",fontSize = 22.sp)}}

推荐阅读