android mvvm实例解析

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!!
}
}
}
android mvvm实例解析的更多相关文章
- 【转】Android HAL实例解析
原文网址:http://www.embedu.org/Column/Column339.htm 作者:刘老师,华清远见嵌入式学院讲师. 一.概述 本文希望通过分析台湾的Jollen的mokoid 工程 ...
- Android HAL实例解析
一.概述 本文希望通过分析台湾的Jollen的mokoid 工程代码,和在s5pc100平台上实现过程种遇到的问题,解析Andorid HAL的开发方法. 二.HAL介绍 现有HAL架构由Patric ...
- Android AIDL实例解析
AIDL这项技术在我们的开发中一般来说并不是很常用,虽然自己也使用新浪微博的SSO登录,其原理就是使用AIDL,但是自己一直没有动手完整的写过AIDL的例子,所以就有了这篇简单的文章. AIDL(An ...
- Android实例-Delphi开发蓝牙官方实例解析(XE10+小米2+小米5)
相关资料:1.http://blog.csdn.net/laorenshen/article/details/411498032.http://www.cnblogs.com/findumars/p/ ...
- Android开发之IPC进程间通信-AIDL介绍及实例解析
一.IPC进程间通信 IPC是进程间通信方法的统称,Linux IPC包括以下方法,Android的进程间通信主要采用是哪些方法呢? 1. 管道(Pipe)及有名管道(named pipe):管道可用 ...
- Android Service完全解析,关于服务你所需知道的一切(上)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...
- [转] Android Volley完全解析(一),初识Volley的基本用法
版权声明:本文出自郭霖的博客,转载必须注明出处. 目录(?)[-] Volley简介 下载Volley StringRequest的用法 JsonRequest的用法 转载请注明出处:http ...
- Android IntentService完全解析 当Service遇到Handler
一 概述 大家都清楚,在Android的开发中,凡是遇到耗时的操作尽可能的会交给Service去做,比如我们上传多张图,上传的过程用户可能将应用置于后台,然后干别的去了,我们的Activity就很可能 ...
- Android Volley完全解析
1. Volley简介 我们平时在开发Android应用的时候不可避免地都需要用到网络技术,而多数情况下应用程序都会使用HTTP协议来发送和接收网络数据.Android系统中主要提供了两种方式来进行H ...
- Android Bitmap 全面解析(四)图片处理效果对比 ...
对比对象: UIL Volley 官方教程中的方法(此系列教程一里介绍的,ImageLoader的处理方法和官方的差不多) -------------------------------------- ...
随机推荐
- Avalonia使用默认弹窗
Avalonia使用默认弹窗 在Avalonia中使用官方默认弹窗WindowNotificationManager Views\MainWindow.axaml相关代码 <Window xml ...
- SV Clocking Review
clocking会设置input和output的延时 default input #3ns output #1ns 数据是在时钟上升沿驱动的,在时钟上升沿,将vld驱动到dut,dut中也会在时钟上升 ...
- 基于AHB_BUS的eFlash控制器的架构设计
eFlash控制器的架构设计 1.架构设计思路分析 1.1 含有的模块分析 eFlash控制器是一个基于AHB的slave,所以需要一个AHB_slave_if处理AHB的信号.AHB_slave_i ...
- Django应用中的静态文件处理
在日常开发中,我们都是把Django的Debug模式打开,方便调试,在这个模式下,由Django内置的Web服务器提供静态文件服务,不过需要进行一些配置,才能正确访问. 配置settings # St ...
- [转帖]Linux nice和renice命令:改变进程优先级
https://c.biancheng.net/view/1074.html 当 Linux 内核尝试决定哪些运行中的进程可以访问 CPU 时,其中一个需要考虑的因素就是进程优先级的值(也称为 nic ...
- [转帖]解决Harbor在服务器重启后无法自启动的问题
问题 当部署Harbor的服务器在重启之后,可能会出现Harbor无法跟随系统自启动 解决方案 现假设Harbor的安装目录位置为/usr/local/harbor,在Harbor安装完成之后,在此目 ...
- [转帖]如何使用 sed 命令删除文件中的行
https://zhuanlan.zhihu.com/p/80212245 sed 命令是 Linux 中的重要命令之一,在文件处理方面有着重要作用.可用于删除或移动与给定模式匹配的特定行.-- Ma ...
- [转帖]PyCharm无法安装第三方模块,一直提示 updating list:time out 解决办法
Pycharm无法安装第三方模块解决办法: 1.打开pycharm的项目的venv文件夹 2.打开文件夹目录中的pyvenv文件 3.将文件中的include-system-site-packages ...
- [转帖]一次操作系统报错OutOfMemory Error的处理记录
在启动公司内嵌的tomcat容器时出现报错, 如下: # There is insufficient memory for the Java Runtime Environment to contin ...
- echarts在左下角添加单位
配置单位 option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], ...