因为如果把dialog写在viewmodel里面,之後在自动化测试的时候可能会出问题,所以在mvvm架构底下,我们另外写了一个dialogviewmodel,对应到dialog的view
首先先建立一个dialogviewmodel
class DialogViewModel: ViewModel() {
val result: MutableLiveData = MutableLiveData()
}
然後建立一个状态资讯
//表达一个元件的状态
//sealed可以使用dataclass传值
sealed class MainDialogResult {
data class Ok(val message: String): MainDialogResult()
object Cancel: MainDialogResult()
//也可以使用object变成跟enum一样的用法
}
然後在dialogfragment中这样调用
class FragmentDialog: DialogFragment() {
private val viewModel: DialogViewModel<MainDialogResult> by activityViewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.dialogfragment , container , false)
val accountEditView = view.findViewById<EditText>(R.id.account)
val passwordEditView = view.findViewById<EditText>(R.id.password)
val loginButton = view.findViewById<Button>(R.id.login)
val cancelButton = view.findViewById<Button>(R.id.cancel)
val progressBar = view.findViewById<ProgressBar>(R.id.progressBar)
val pgBar = view.findViewById<ProgressBar>(R.id.progressBar2)
progressBar.visibility = View.VISIBLE
pgBar.max = 100
Thread{
for (i in 0..100){
pgBar.progress = i
//Thread.sleep(500)
SystemClock.sleep(500)
}
}.start()
pgBar.progress = 0
val message = "ok"
loginButton.setOnClickListener {
viewModel.result.postValue(MainDialogResult.Ok(message))
dismiss()
}
cancelButton.setOnClickListener {
viewModel.result.postValue(MainDialogResult.Cancel)
dismiss()
}
return view
}
}
最後在activity中这要调用即可
val fm = supportFragmentManager
val dialog = FragmentDialog()
dialog.show(fm,"Blossom")
viewModel.result.observe(this){
when(it){
is MainDialogResult.Ok ->{
Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
}
is MainDialogResult.Cancel ->{
Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
}
}
学习目标 本文章将会是阅读官方文件Add navigation with routing 内容所做的...
Redis丛集Slot分流机制 # Redis丛集配置 client | V -----------...
近年微服务架构兴起,对於规模较小的开发团队而言,一开始就拆分为多个微服务是个沉重的负担,所以大多还是...
上一篇利用 Angular 路由机制实作待办事项清单与表单页面的切换,这一篇将路由的参数或资料的定义...
看完这篇文章你会得到的成果图 多了一条滑条,我们可以直接控制,另外我们也可以直接透过滑条来操控进度 ...