简介
使用的技术是观察者与被观察者的模式,在google推荐的案例中也有使用到,现在我把它封装成一个扩展函数,使得使用更加简单明了
注意
TextView显示的值随activity的属性值改变同时改变–LiveData
代码
MainActivity
class MainActivity : AppCompatActivity() {
private val mutableLiveData = MutableLiveData<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tv2.bindValue(mutableLiveData,this)
bt1.setOnClickListener {
// 第二种使用扩展函数封装好的模式
mutableLiveData.value="我爱李曼娜"
}
}
/**
* TextView的扩展函数
* 使用方法:
* val mutableLiveData = MutableLiveData<String>()
* tv2.bindValue(mutableLiveData,this)
*
* 在按钮事件里调用:mutableLiveData.value="我爱你"
* TextView中显示的值就会跟着改变
*/
fun TextView.bindValue( mutableLiveData:MutableLiveData<String>,lifecycleOwner:LifecycleOwner){
var text1: LiveData<String> = Transformations.map(mutableLiveData) {
// "观察者: $it"
it
}
text1.observe(lifecycleOwner, Observer<String> {
this.text = it
})
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="赋值3"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>