RecyclerView OnClick Listener again
Note: In this post, I just show only some methods where you have to change not full code.
Benefits of the methods are you can use this click listener in your activity, not adapter class.
If you want to learn about full recycle view code like the adapter and viewHolder class sees this post.
Processes-
1. First, you need to add an interface (you can add interface in separate interface file or declare in on inner class). I add on Adapter class
public interface ClickListener{ void onItemClickListener(String s); }Note: If you need long click listener then create another method and add on view holder class. I add a method on interface name OnItemClickListener and add parameter String because we need a string to send another activity.
2.Now modify the default constructor of adapter class
private ClickListener clickListener; /** * Constructor for the CustomCursorAdapter * @param clickListener to handle click event */ public CustomCursorAdapter(ClickListener clickListener) { this.clickListener = clickListener; }3. Implements view.OnClickListener on viewHolder class. See this
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // Class variables for the task description and priority TextViews TextView word; /** * Constructor for the TaskViewHolders. * * @param itemView The view inflated in onCreateViewHolder */ private MyViewHolder(View itemView) { super(itemView); word = (TextView) itemView.findViewById(R.id.mainRecycleView_TV); word.setOnClickListener(this); } @Override public void onClick(View v) { mCursor.moveToPosition(getAdapterPosition()); int wordIndex = mCursor.getColumnIndex(COLUMN_WORD); String word = mCursor.getString(wordIndex); //get word from cursor and set it to click listener parameter // we can easily access form click event methods clickListener.onItemClickListener(word); } }on the Onclick listener method, we take String from array or Cursor and send as our interface method parameter. Now can easily access this string on the main activity. 4. Now time to Use - implements the interface that's we created earlier,
public class MainActivity extends AppCompatActivity implements CustomCursorAdapter.ClickListener { //some code }After that's
/** onClick listener for recycler view * called if click any item on recycler view * @param word is the selected word from data base */ @Override public void onItemClickListener(String word) { Intent intent = new Intent(MainActivity.this, DetailsActivity.class); intent.putExtra(Intent.EXTRA_TEXT,word); startActivity(intent); }Using adapter
CustomCursorAdapter mAdapter = new CustomCursorAdapter(this); recyclerView.setAdapter(mAdapter);Thanks for reading this post.
I hope your code is running well. And you can handle the click event on RecyclerView more easily. But once again full code post of recyclerview is here.
If you have any queries then use comment option I will help you.
Happy coding :p
No comments :