RecyclerView アイテム内ある要素の クリックイベント

いろんな実装が可能なのですが.


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;  
        // ...
  }

    // ...
}

ここらなんだろうな.

java - Why doesn't RecyclerView have onItemClickListener()? And how RecyclerView is different from Listview? - Stack Overflow


関連ワード:  Androidライブラリ今さら聞けない開発