我通常在活動或片段中保存對適配器的引用。 ViewHolders可以作爲Adapter中的內部類或者作爲獨立包中的類來放置。您可以使用一個界面與視圖持有者進行交互。你只需要在你的活動或片段中實現它。例如:
public class MyAdapter extends RecyclerView.Adapter<VH> {
private MyInterface mInterface;
public MyAdapter(MyInterface i) {
mInterface = i;
}
//... some code to create view holders
//binding
@Override
protected void onBindItemViewHolder(ViewHolder viewHolder, final int position, int type) {
viewHolder.bindView(position, mInterface); //call methods of interface in bindView() methods of your viewHolders
}
interface MyInterface {
void someEvent();
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mText;
ViewHolder(View root) {
super(root);
mText = (TextView)root.findViewById(R.id.text)
}
void bindView(int pos, MyAdapter.MyInterface myInterface) {
mText.setOnClickListener(v -> myInterface.someEvent());
//...some other code
}
}
在活動或片段
而且地方:
final MyAdapter adapter = new MyAdapter(new MyAdapter.MyInterface() {
@Override
public void someEvent() {
adapter.notifyDataSetChanged();
}
});
你也可以使用數據綁定。 – BlackHatSamurai