val 就是 value
var 就是 variable 简写
var number:Int = 0
var l:String = "888"
设置启动页的 Activity
package com.lyr.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_example.*
class ExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_example)
var number = 0
this.textView.text = ""
btn_add.setOnClickListener{
textView.text = (number++).toString()
}
btn_decr.setOnClickListener{
textView.text = (number--).toString()
}
}
}
package com.lyr.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.lyr.myapplication.vm.MyViewModel
import kotlinx.android.synthetic.main.activity_example.*
class ExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_example)
val vm :MyViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// this.textView.text = vm.number.value.toString()
vm.number.observe(this, Observer{
textView.text = it.toString()
})
btn_add.setOnClickListener{
vm.modifyNumber(1)
}
btn_decr.setOnClickListener{
// textView.text = (number--).toString()
vm.modifyNumber(-1)
}
}
}
package com.lyr.myapplication.vm
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
/**
* view model
* @Author lyr
* @create 2020/10/11 20:11
*/
class MyViewModel : ViewModel() {
val number: MutableLiveData<Int> by lazy {
MutableLiveData<Int>().also {
it.value = 0
}
}
fun modifyNumber(n:Int) {
number.value = number.value?.plus(n)
// //强制执行
// number.value = number.value!!.plus(n)
}
}
getter 方式的写法
class MyViewModel : ViewModel() {
private val _number: MutableLiveData<Int> by lazy {
MutableLiveData<Int>().also {
it.value = 0
}
}
val number: LiveData<Int> get() = _number
fun modifyNumber(n: Int) {
_number.value = _number.value?.plus(n)
// //强制执行
// number.value = number.value!!.plus(n)
}
}