有时在RecyclerView适配器中,单击每一行中的项目时调用函数会很有帮助,因此我定义了一个接口并分配了侦听器,如下所示:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.RecyclerViewHolder> {
private List<SomeObject> mSomeObjectList;
private Context mContext;
private RowClickListener mListener;
public interface RowClickListener {
void someFunction(SomeObject someObject);
}
public MyRecyclerViewAdapter(Context context, List<SomeObject> objects) {
mContext = context;
mSomeObjectList = objects;
mListener = (RowClickListener) context;
}
//...
这是正确的方法吗?我注意到,当人们在Fragment类中分配侦听器时,他们通常在OnAttach方法中执行此操作,对于Adapter来说,它似乎并不存在。在这里合适的地方是什么?
最佳答案
宁愿在Adapter
中定义它,也建议在Fragment
或Activity
中使用它。
为Interface
定义单独的类或在Fragment/Activity
中定义它。
public class SomeActivity extends Activity implements RowClickListener
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
.
MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(context,list,this);
}
@Override
public void someFunction(SomeObject someObject){
}
}
public interface RowClickListener {
void someFunction(SomeObject someObject);
}
并在您的适配器类中
private RowClickListener mListener;
public MyRecyclerViewAdapter(Context context, List<SomeObject> objects, RowClickListener listener) {
mContext = context;
mSomeObjectList = objects;
mListener = listener;
}