我想使用数据绑定库和ViewModel
这是我的XML文件(当前onclick在RelativeLayout上)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="orgmembvm"
type="com.support.android.designlibdemo.include.OrgMemb" />
<variable name="orgmembhandlers"
type="com.support.android.designlibdemo.View.MyOrgMembHandlers"/>
</data>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp">
<RelativeLayout
android:id="@+id/org_memb_rec"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="@{orgmembhandlers::onClickOpenEditRec}"
android:padding="8dp">
//Inner Child element
</RelativeLayout>
适配器的BindViewHolder
@Override
public void onBindViewHolder(@NonNull OrgMembViewHolder holder, int
position) {
holder.mBinding.setOrgmembvm(orgMembArrayList.get(position));
holder.mBinding.setOrgmembhandlers(new MyOrgMembHandlers());
holder.mBinding.executePendingBindings();
}
Activity类中的代码,用于将viewModel附加到Activity。
@Override
protected void onCreate(Bundle savedInstanceState) {
......
......
userModel = ViewModelProviders.of(this).get(OrgMembViewModel.class);
userModel.getAllLive().observe(this, orgMembList -> {
mAdapter.updateorgmemblist(orgMembList);
});
}
如何实现?
答案 0 :(得分:2)
<variable
name="position"
type="int"/>
@Override
public void onBindViewHolder(@NonNull OrgMembViewHolder holder, int position) {
holder.mBinding.setPosition(position);
}
onClickOpenEditRec
参数public class MyOrgMembHandler {
public void onClickOpenEditRec(int position) {
}
}
android:onClick="@{()->orgmembhandlers.onClickOpenEditRec(position)}"
Check this answer,了解在数据绑定中设置点击的方式。