class ChooseAreaFragment : Fragment() { private val viewModel by lazy { ViewModelProviders.of(this, InjectorUtil.getChooseAreaModelFactory()).get(ChooseAreaViewModel::class.java) } private var progressDialog: ProgressDialog? = null private lateinit var adapter: ArrayAdapter<String> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.choose_area, container, false) val binding = DataBindingUtil.bind<ChooseAreaBindingImpl>(view) binding?.viewModel = viewModel return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) adapter = ChooseAreaAdapter(context!!, R.layout.simple_item, viewModel.dataList) listView.adapter = adapter observe() } private fun observe() { viewModel.currentLevel.observe(this, Observer { level -> when (level) { LEVEL_PROVINCE -> { titleText.text = "中国" backButton.visibility = View.GONE } LEVEL_CITY -> { titleText.text = viewModel.selectedProvince?.provinceName backButton.visibility = View.VISIBLE } LEVEL_COUNTY -> { titleText.text = viewModel.selectedCity?.cityName backButton.visibility = View.VISIBLE } } }) viewModel.dataChanged.observe(this, Observer { adapter.notifyDataSetChanged() listView.setSelection(0) closeProgressDialog() }) viewModel.isLoading.observe(this, Observer { isLoading -> if (isLoading) showProgressDialog() else closeProgressDialog() }) viewModel.areaSelected.observe(this, Observer { selected -> if (selected && viewModel.selectedCounty != null) { if (activity is MainActivity) { val intent = Intent(activity, WeatherActivity::class.java) intent.putExtra("weather_id", viewModel.selectedCounty!!.weatherId) startActivity(intent) activity?.finish() } else if (activity is WeatherActivity) { val weatherActivity = activity as WeatherActivity weatherActivity.drawerLayout.closeDrawers() weatherActivity.viewModel.weatherId = viewModel.selectedCounty!!.weatherId weatherActivity.viewModel.refreshWeather() } viewModel.areaSelected.value = false } }) if (viewModel.dataList.isEmpty()) { viewModel.getProvinces() } } /** * 显示进度对话框 */ private fun showProgressDialog() { if (progressDialog == null) { progressDialog = ProgressDialog(activity) progressDialog?.setMessage("正在加载...") progressDialog?.setCanceledOnTouchOutside(false) } progressDialog?.show() } /** * 关闭进度对话框 */ private fun closeProgressDialog() { progressDialog?.dismiss() } companion object { const val LEVEL_PROVINCE = 0 const val LEVEL_CITY = 1 const val LEVEL_COUNTY = 2 } }
class ChooseAreaViewModel(private val repository: PlaceRepository) : ViewModel() { var currentLevel = MutableLiveData<Int>() var dataChanged = MutableLiveData<Int>() var isLoading = MutableLiveData<Boolean>() var areaSelected = MutableLiveData<Boolean>() var selectedProvince: Province? = null var selectedCity: City? = null var selectedCounty: County? = null lateinit var provinces: MutableList<Province> lateinit var cities: MutableList<City> lateinit var counties: MutableList<County> val dataList = ArrayList<String>() fun getProvinces() { currentLevel.value = LEVEL_PROVINCE launch { provinces = repository.getProvinceList() dataList.addAll(provinces.map { it.provinceName }) } } private fun getCities() = selectedProvince?.let { currentLevel.value = LEVEL_CITY launch { cities = repository.getCityList(it.provinceCode) dataList.addAll(cities.map { it.cityName }) } } private fun getCounties() = selectedCity?.let { currentLevel.value = LEVEL_COUNTY launch { counties = repository.getCountyList(it.provinceId, it.cityCode) dataList.addAll(counties.map { it.countyName }) } } fun onListViewItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { when { currentLevel.value == LEVEL_PROVINCE -> { selectedProvince = provinces[position] getCities() } currentLevel.value == LEVEL_CITY -> { selectedCity = cities[position] getCounties() } currentLevel.value == LEVEL_COUNTY -> { selectedCounty = counties[position] areaSelected.value = true } } } fun onBack() { if (currentLevel.value == LEVEL_COUNTY) { getCities() } else if (currentLevel.value == LEVEL_CITY) { getProvinces() } } private fun launch(block: suspend () -> Unit) = viewModelScope.launch { try { isLoading.value = true dataList.clear() block() dataChanged.value = dataChanged.value?.plus(1) isLoading.value = false } catch (t: Throwable) { t.printStackTrace() Toast.makeText(CoolWeatherApplication.context, t.message, Toast.LENGTH_SHORT).show() dataChanged.value = dataChanged.value?.plus(1) isLoading.value = false } } }
class PlaceRepository private constructor(private val placeDao: PlaceDao, private val network: CoolWeatherNetwork) { suspend fun getProvinceList() = withContext(Dispatchers.IO) { var list = placeDao.getProvinceList() if (list.isEmpty()) { list = network.fetchProvinceList() placeDao.saveProvinceList(list) } list } suspend fun getCityList(provinceId: Int) = withContext(Dispatchers.IO) { var list = placeDao.getCityList(provinceId) if (list.isEmpty()) { list = network.fetchCityList(provinceId) list.forEach { it.provinceId = provinceId } placeDao.saveCityList(list) } list } suspend fun getCountyList(provinceId: Int, cityId: Int) = withContext(Dispatchers.IO) { var list = placeDao.getCountyList(cityId) if (list.isEmpty()) { list = network.fetchCountyList(provinceId, cityId) list.forEach { it.cityId = cityId } placeDao.saveCountyList(list) } list } companion object { private var instance: PlaceRepository? = null fun getInstance(placeDao: PlaceDao, network: CoolWeatherNetwork): PlaceRepository { if (instance == null) { synchronized(PlaceRepository::class.java) { if (instance == null) { instance = PlaceRepository(placeDao, network) } } } return instance!! } } }
文章来源地址https://www.toymoban.com/news/detail-624438.html
文章来源:https://www.toymoban.com/news/detail-624438.html
到了这里,关于android mvvm实例解析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!