Cómo agregar el oyente Onclick a la vista de reciclador

Estoy desarrollando una aplicación de bloc de notas simple primero utilicé listView para mostrar todas las notas. Pero ahora estoy usando RecyclerView. Mientras estoy usando listview, utilicé OnItemClickListener para pasar los datos a otra actividad para editar la nota, ahora confundo qué hacer en Recylerview.

Para listView, estoy usando esto

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { name = filenames.get(position).getName(); note = filenames.get(position).getShorttext(); Alert(); // this method is in main activity } });*/ public void Alert() { final AlertDialog dialog; View mview = getLayoutInflater().inflate(R.layout.dialog_pass,null); final EditText mEdittext = (EditText) mview.findViewById(R.id.Epass); AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this); mBuilder.setView(mview); mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String col = mEdittext.getText().toString(); String password = dBhelper.searchpass(col); if (col.equals(password)) { Intent intent = new Intent(MainActivity.this,Note2.class); intent.putExtra("Name",name); intent.putExtra("Note",note); startActivity(intent); } else { Toast temp = Toast.makeText(MainActivity.this, "Password does not match", Toast.LENGTH_SHORT); temp.show(); } } }); mBuilder.setNegativeButton("Cancel",null); mBuilder.setCancelable(false); dialog = mBuilder.create(); dialog.show(); } 

Ahora, ¿qué debo hacer para reciclar vista? Por favor ayuda

  public class RecycleViewAdapter extends RecyclerView.Adapter {// Recyclerview will extend to private List fileNames; private Context context; public RecycleViewAdapter(Context context,List fileNames) { this.context = context; this.fileNames = fileNames; 

}

 @Override public RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater mInflater = LayoutInflater.from(parent.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate( R.layout.grid_item, parent, false); RecycleViewHolder listHolder = new RecycleViewHolder(mainGroup); return listHolder; } @Override public void onBindViewHolder(RecycleViewHolder holder, final int position) { final FileName model = fileNames.get(position); RecycleViewHolder mainHolder = (RecycleViewHolder) holder;// holder mainHolder.title.setText(model.getName()); mainHolder.note.setText(model.getShorttext()); } @Override public int getItemCount() { return (null != fileNames ? fileNames.size() : 0); } 

Puedes manejar esto usando dos formas

1). Gesto táctil https://www.google.co.in/amp/sapandiwakar.in/recycler-view-item-click-handler/amp/

2) .Usando la interfaz en el adaptador https://antonioleiva.com/recyclerview-listener/

Sugiero una segunda forma de usar la interfaz

Cómo usar la interfaz para recycleritemclick

 public class RecycleViewAdapter extends RecyclerView.Adapter {// Recyclerview will extend to private List fileNames; private Context context; //declare interface private OnItemClicked onClick; //make interface like this public interface OnItemClicked { void onItemClick(int position); } public RecycleViewAdapter(Context context,List fileNames) { this.context = context; this.fileNames = fileNames; 

Ahora asigne clic a la interfaz

  @Override public void onBindViewHolder(RecycleViewHolder holder, final int position) { //............// holder.title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClick.onItemClick(position); } }); } 

Al final de la clase de adaptador desde el soporte de acabado, haga un método para asignar el elemento a la interfaz

 public void setOnClick(OnItemClicked onClick) { this.onClick=onClick; } 

En MainActivity.java Enlace el elemento, haga clic en el adaptador

 public class MainActivity extends Activity implements OnItemClicked { private RecyclerView mRecyclerView; private CityAdapter mAdapter; private List cities; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_city); mRecyclerView = (RecyclerView)findViewById(R.id.list); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new CityAdapter(cities, R.layout.row_city, this); mRecyclerView.setAdapter(mAdapter); mAdapter.setOnClick(MainActivity.this); // Bind the listener } @Override public void onItemClick(int position) { // The onClick implementation of the RecyclerView item click //ur intent code here } 

Espero que esto te ayude si necesitas ayuda puedes preguntar

La solución más simple sería acceder a la variable pública “itemView” de la clase de titular y configurar OnClickListener en esto.

 @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, NewActivity.class); intent.putExtra("FileName", list.get(position)); context.startActivity(intent); } }); } 

Agregue este código en su adaptador RecyclerView

  private OnItemClicked mListener; public RecycleViewAdapter(Context context, OnItemClicked listener, List fileNames) { //............// this.mListener = listener; } @Override public void onBindViewHolder(RecycleViewHolder holder, final int position) { //............// mainHolder.title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onItemClick(position); } }); } public interface OnItemClicked { void onItemClick(int position); } 

E implemente su Actividad / Fragmento a RecyclerViewAdapter.OnItemClicked

Para pasar a través de Intento puedes escribir el código a continuación en tu Actividad / Fragmento

  @Override public void onItemClick(int position) { Intent intent = new Intent(mContext, YourActivity.class); intent.putExtra(YourActivity.ARG_FILE, filnames.get(position)); startActivity(intent); } 

Cambie su adaptador a este

  public class RecycleViewAdapter extends RecyclerView.Adapter {// Recyclerview will extend to private List fileNames; private Context context; private OnItemClicked listener; public RecycleViewAdapter(Context context, List fileNames, OnItemClicked listener) { this.context = context; this.fileNames = fileNames; this.listener = listener; } public BookingHistoryFragment() { // Required empty public constructor } @Override public RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater mInflater = LayoutInflater.from(parent.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate( R.layout.grid_item, parent, false); RecycleViewHolder listHolder = new RecycleViewHolder(mainGroup); return listHolder; } @Override public void onBindViewHolder(RecycleViewHolder holder, final int position) { final FileName model = fileNames.get(position); RecycleViewHolder mainHolder = (RecycleViewHolder) holder;// holder mainHolder.title.setText(model.getName()); mainHolder.note.setText(model.getShorttext()); // Add click listener for root view view.getRootView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listener.onItemClick(view, position) } }); } @Override public int getItemCount() { return (null != fileNames ? fileNames.size() : 0); } public interface OnItemClicked { void onItemClick(View view, int position); } } 

Ahora pase ItemClickInterface al constructor del adaptador al inicializar desde actividad o fragmento. En lugar de:

 RecycleViewAdapter adapter = new RecycleViewAdapter(this, filenames); 

Utilizar esta:

 RecycleViewAdapter adapter = new RecycleViewAdapter(this, filenames, new RecycleViewAdapter.OnItemClicked () { @Override public void onItemClick(View view, Position position) { } }); 

Primero agregue esta clase a su paquete

 public class MyTouchListener implements RecyclerView.OnItemTouchListener { /*Change these as per your need*/ private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private static final int SWIPE_MAX_OFF_PATH = 250; private OnTouchActionListener mOnTouchActionListener; private GestureDetectorCompat mGestureDetector; public static interface OnTouchActionListener { public void onLeftSwipe(View view, int position); public void onRightSwipe(View view, int position); public void onClick(View view, int position); } public MyTouchListener(Context context, final RecyclerView recyclerView, OnTouchActionListener onTouchActionListener){ mOnTouchActionListener = onTouchActionListener; mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){ @Override public boolean onSingleTapConfirmed(MotionEvent e) { // Find the item view that was swiped based on the coordinates View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); int childPosition = recyclerView.getChildPosition(child); mOnTouchActionListener.onClick(child, childPosition); return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) { return false; } // Find the item view that was swiped based on the coordinates View child = recyclerView.findChildViewUnder(e1.getX(), e1.getY()); int childPosition = recyclerView.getChildPosition(child); // right to left swipe if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (mOnTouchActionListener != null && child != null) { mOnTouchActionListener.onLeftSwipe(child, childPosition); } } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (mOnTouchActionListener != null && child != null) { mOnTouchActionListener.onRightSwipe(child, childPosition); } } } catch (Exception e) { // nothing } return false; } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { mGestureDetector.onTouchEvent(e); return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { // do nothing }} 

Luego addOnItemTouchListener así:

 myRecyclerView.addOnItemTouchListener(new MyTouchListener(mContext, myRecyclerView, new MyTouchListener.OnTouchActionListener() { @Override public void onLeftSwipe(View view, int position) {//code as per your need } @Override public void onRightSwipe(View view, int position) {//code as per your need } @Override public void onClick(View view, int position) {//code as per your need } })); 

Entonces, no estoy seguro de si alguien está interesado o si hay problemas con mi método, pero se me ocurrió un método mucho más simple para mi uso personal.

Xml del artículo:

     

Dentro de onBindViewHolder, establece la etiqueta igual a la información que necesites. El nombre, la posición, el texto que se muestra, la imagen que se muestra, lo que sea.

 @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.recycText.setText(lstAllInfo.get(position)); holder.recycText.setTag(lstAllInfo.get(position)); } 

En su método en el que desea manejar el elemento, haga clic en:

  public void recycClick(View v) { String test = v.getTag().toString(); Toast.makeText(getApplicationContext(), ("You clicked: " + test), Toast.LENGTH_LONG).show(); } 

Supongo que hay limitaciones a esto. Tag puede no ser capaz de contener los datos que necesita, o es posible que la vista de reciclaje no haya podido acceder a la actividad correcta para el clic. Personalmente lo estoy usando para Android Wear y funciona muy bien, así que pensé en publicarlo por si acaso, ya que es mucho menos trabajo que los otros métodos.