kotlin 语法介绍

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)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值