[英]Android: pass lambda to recycler adapter by android data binding
I am using mvvm and data binding on my project.I have a recycler view and make an adapter.my data shown in recycler view fine.Now i want to create item click listener.我在我的项目上使用 mvvm 和数据绑定。我有一个回收器视图并制作一个适配器。我的数据显示在回收器视图中。现在我想创建项目点击侦听器。
So at the end of my adapter i create an interface like this:所以在我的适配器的最后,我创建了一个这样的界面:
interface MyClickListener {
void onItemClick(MyEntity myEntity);
}
after that i added this listener to constructor of my adapter:之后,我将此侦听器添加到我的适配器的构造函数中:
public class MyRecyclerAdapter extends ListAdapter<MyEntity, MyRecyclerAdapter.ViewHolder> {
public MyClickListener clickListener;
public MyRecyclerAdapter(MyClickListener clickListener) {
super(MyEntity.DIFF_CALLBACK);
this.clickListener = clickListener;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
MyEntity item = getItem(position);
holder.bind(item,clickListener);
}
and i send my callback to bind view xml :我将回调发送到绑定视图 xml :
private void bind(MyEntity item, MyClickListener clickListener) {
binding.setEntity(item);
binding.setClickListener(clickListener);
binding.executePendingBindings();
}
In xml:在 xml 中:
<?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="entity"
type="com.test.database.myEntity" />
<variable
name="clickListener"
type="com.test.home.MyClickListener" />
</data>
<androidx.cardview.widget.CardView
android:id="@+id/cardview_id"
android:layout_width="190dp"
android:layout_height="280dp"
android:layout_margin="5dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardBackgroundColor="@android:color/white"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
app:cardUseCompatPadding="true"
android:onClick="@{() -> clickListener.onItemClick(entity)}">
and i initialize this callback in my adapter:我在我的适配器中初始化这个回调:
MyRecyclerAdapter adapter = new MyRecyclerAdapter(myEntity -> {
Toast.makeText(getContext(), myEntity.getID(), Toast.LENGTH_SHORT).show();
});
But when i run application i got this error:但是当我运行应用程序时,我收到了这个错误:
error: cannot find symbol class MyClickListener
What is my mistake?我的错误是什么?
I have to make class instead of interface and make a new object?我必须创建类而不是接口并创建一个新对象? There is no way to use interface ?有没有办法使用接口?
It's an issue related to access modifier of your interface
.这是与interface
访问修饰符相关的问题。 Try to change it public
尝试将其更改为public
public interface MyClickListener {
void onItemClick(MyEntity myEntity);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.