いろんな実装が可能なのですが.
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ViewHolder> {
// ...
private static ItemsAdapter.OnItemClickListener listener;
public void setOnItemClickListener(ItemsAdapter.OnItemClickListener listener) {
ItemsAdapter.listener = listener;
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
// ...
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(final View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
age = (TextView) itemView.findViewById(R.id.age);
button = (Button) itemView.findViewById(R.id.button);
name.setOnClickListener(this);
age.setOnClickListener(this);
button.setOnClickListener(this)
}
@Override
public void onClick(View v) {
if (listener != null) {
listener.onItemClick(v, getLayoutPosition());
}
}
}
}
UI.
public class MainFragment extends Fragment
implements ItemsAdapter.OnItemClickListener {
// ...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...
mAdapter.setOnItemClickListener(this);
}
@Override
public void onItemClick(View view, int position) {
switch (view.getId()) {
case R.id.name:
// ...
break;
// ...
}
// ...
}
ここらなんだろうな.
関連ワード: Android・ライブラリ・今さら聞けない・開発・onItemClick・recyclerview