我有一个对象可以填充我的 xml 中的一些字段,但是 mutablelivedata 返回一个 T 值,我不能使用 T 属性。我需要做什么才能在我的 xml 中使用 T 对象?
我不想为每个对象成员创建一个 mutablelivedata。
对不起,我的英语不好..
class ExampleFragment: Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val viewModel = ViewModelProviders.of(this).get(MyVm::class.java)
val binding = DataBindingUtil.inflate<FragmentExampleBinding>(
inflater,
R.layout.fragment_house,
container,
false
)
binding.myVm = viewModel
binding.lifecycleOwner = this
return binding.root
}
}
class MyVm: ViewModel(){
val house: MutableLiveData<House> by lazy { MutableLiveData<House>().apply{ value =
House().apply{
door = "First door"
window = "My window"
}
} }
val thing: MutableLiveData<String> by lazy { MutableLiveData<String>().apply{ value = "something" } }
}
class House(){
var door: String = ""
var window: String = ""
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable name="my_vm" type="br.com.MyVm"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
orientation="vertical"
>
<!--I need this work-->
<TextView
android:layout_width="wrap_parent"
android:layout_height="wrap_parent"
android:text="my_vm.house.door"
/>
<!--I need this work-->
<TextView
android:layout_width="wrap_parent"
android:layout_height="wrap_parent"
android:text="my_vm.house.window"
/>
<TextView
android:layout_width="wrap_parent"
android:layout_height="wrap_parent"
android:text="my_vm.thing"
/>
</LinearLayout>
<layout>