继Google的android数据绑定之后,我一直在代码中删除findViewById()
。
我有一个回收站视图,其中包含特定项目视图中每个按钮的单击侦听器。我正在尝试寻找一种在这种特殊情况下消除findViewById()
方法的方法。
MainFragment.java文件中的代码段:
// Add touch listener for the recycler view
mainFragmentBinding.mainFragmentFoodItemsRecyclerView.addOnItemTouchListener(
new RecyclerTouchListener(
getContext(),
mainFragmentBinding.mainFragmentFoodItemsRecyclerView,
new ClickListener() {
@Override
public void onClick(View view, final int position) {
Button addButton = view.findViewById(R.id.food_add_button);
addButton.setOnClickListener(addButtonView -> {
// Notify user
Toast.makeText(getContext(), "Clicked on Add button",
Toast.LENGTH_SHORT).show();
});
// Values are passing to activity & to fragment as well
Toast.makeText(
getContext(),
"Single Click on position : " + position,
Toast.LENGTH_SHORT
).show();
}
@Override
public void onLongClick(View view, int position) {
Toast.makeText(
getContext(),
"Long press on position : " + position,
Toast.LENGTH_LONG
).show();
}
}
));
我要从以上代码段更改的行:
Button addButton = view.findViewById(R.id.food_add_button);
这可能吗?如果是,有人可以帮我吗?
还是应该保留findViewById()
方法?
答案 0 :(得分:2)
是的,您可以替换它,也许应该替换。
为此,请首先为数据绑定准备商品布局,然后在其中添加click回调:
?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="item"
type="com.example.your.item.Type"/>
<variable
name="parentViewModel"
type="com.example.your.viewmodel.Type"/>
</data>
<YourLayout
...
android:onClick="@{() -> parentViewModel.onItemClicked(item)}"
...
YourLayout />
</layout>
在视图持有者中,声明一个属性,以保存对可绑定项目布局的引用:
lateinit var binding: YoutItemLayoutBindable
在适配器的onCreateViewHolder(...)
内,确保您使用数据绑定来增加商品布局:
val inflater = LayoutInflater.from(parent.context)
val binding = DataBindingUtil.inflate<YoutItemLayoutBindable>(inflater, R.layout.your_item_layout, parent, false)
val viewHolder = ViewHolder(binding.root)
// Pass your activity/fragment as the lifeCycleOwner when creating the adapter
binding.lifecycleOwner = lifeCycleOwner
// Pass also your viewmodel as a parameter when creating the adapter
binding.parentViewModel = parentViewModel
viewHolder.binding = binding
return viewHolder
然后在onBindViewHolder(...)
内,将该项目设置为绑定的变量:
val item = dataSet[position]
viewHolder.binding.item = item
就是这样!您的代码可能与此示例不同(也许您甚至没有使用viewmodels),但我希望您能理解。