DataBinding (二) Kotlin 简单例子

一、实体并

       1,. 在get方法上增加注解@Bindable

       2. set方法内用notifyPropertyChanged通知数据变化,数据模型变化后由Android系统通知get然后刷新view。

import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR


class UserBean : BaseObservable {
    private var id: String? = null
    private var name: String? = null
    private var blog: String? = null

    constructor() {

    }

    constructor(id: String, name: String, blog: String) {
        this.id = id
        this.name = name
        this.blog = blog
    }

    fun setId(id: String) {
        this.id = id
        notifyPropertyChanged(BR.id)
    }

    @Bindable
    fun getId(): String? {
        return this.id
    }


    fun setName(name: String) {
        this.name = name
        notifyPropertyChanged(BR.name)
    }

    @Bindable
    fun getName(): String? {
        return this.name
    }

    fun setBlog(blog: String) {
        this.blog = blog
        notifyPropertyChanged(BR.blog)
    }

    @Bindable
    fun getBlog(): String? {
        return this.blog
    }
}

二、XML 




    
        
    

    

        

        

        

        
    

三、Activity

class DataBindingActivity : AppCompatActivity() {

    var userBean: UserBean? = null

    companion object {
        // 跳转到当前界面
        fun jump(context: Context) {
            val intent = Intent(context, DataBindingActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置布局
        val contentView = setContentView(this, com.example.goodgoodstudydaydayup.R.layout.activity_data_binding)

        // 创建数据,并进行绑定
        userBean = UserBean("1","张三","www.baidu.con")
        contentView.setUser(userBean)

        change_data.setOnClickListener {
            
            // 刷新user的数据
            userBean?.setId("2")
            userBean?.setName("小仙女")
            userBean?.setBlog("www.taobao.com")
        }
    }


}

你可能感兴趣的:(DataBinding)