我RecyclerView的適配器的構造是這樣的:如何訪問RecyclerView適配器的ViewHolder的數據源?
Context context;
List<ConnectionItem> connections;
public ConnectionsListAdapter(Context context, List connections) {
this.context = context;
this.connections = connections;
}
適配器的聲明後,我宣佈一個靜態ViewHolder類的RecyclerView,也可以用來處理任何按鈕的onClicks:
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Context context;
public ImageView connectionImage;
public TextView connectionName;
public ImageButton startMsg;
public ViewHolder(View itemView, List<ConnectionItem> connections) {
super(itemView);
...
startMsg.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ChatActivity.class);
intent.putExtra("name", connections.get(getAdapterPosition()).getName()); // Error because accessing from static context
intent.putExtra("id", connections.get(getAdapterPosition()).getUid()); // Error because accessing from static context
context.startActivity(intent);
}
}
的問題是connections
無法從ViewHolder靜態類的靜態上下文中訪問。我的ViewHolder從RecyclerView適配器獲取信息的最佳方式是什麼?作爲一種變通方法,我傳遞的數據源到ViewHolder的構造和對於該數據源中的ViewHolder一個新的實例變量:
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Context context;
public List<ConnectionItem> connections;
public ImageView connectionImage;
public TextView connectionName;
public ImageButton startMsg;
public ViewHolder(View itemView, List<ConnectionItem> connections) {
super(itemView);
this.connections = connections;
...
startMsg.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ChatActivity.class);
intent.putExtra("name", connections.get(getAdapterPosition()).getName()); // Okay now
intent.putExtra("id", connections.get(getAdapterPosition()).getUid()); // Okay now
context.startActivity(intent);
}
請問我的路都打破ViewHolder模式或創建任何其他未來的問題?
代替