I have an adapter that customizes a recyclerView
and I want to open a popup menu on long click event on recyclerView
's items. How can I do this?
Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.
you should use recyclerview because it offers more control than listview. It is litte bit complex but you get there then your life will be super easy whenever you are dealing with list kind of thing.
This has already been answered here. Anyway, you can do it like this:
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { private Article article; private TextView nameTextView; public ViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); itemView.setOnLongClickListener(this); nameTextView = (TextView) itemView.findViewById(R.id.grid_item_article_name_textView); } public void bind(Article article) { this.article = article; nameTextView.setText(article.getName()); } @Override public void onClick(View view) { // Context context = view.getContext(); // article.getName() } @Override public boolean onLongClick(View view) { // Handle long click // Return true to indicate the click was handled return true; } }
Update: if you're using Kotlin do:
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener { init { itemView.setOnClickListener(this) itemView.setOnLongClickListener(this) } private lateinit var article: Article private val titleTextView: TextView = itemView.findViewById(R.id.item_article_title_textView) fun bind(article: Article) { this.article = article titleTextView.text = article.title } override fun onClick(view: View) { listener.onItemClick(article) } override fun onLongClick(view: View): Boolean { Toast.makeText(view.context, "long click", Toast.LENGTH_SHORT).show() // Return true to indicate the click was handled return true } }
I did in this way:
static class ViewHolder extends RecyclerView.ViewHolder { TextView tvName; ViewHolder(View v) { super(v); tvName = (TextView) v.findViewById(R.id.textView_Username); //Single Tapup v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "Position is " + getAdapterPosition(), Toast.LENGTH_SHORT).show(); } }); //Long Press v.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(v.getContext(), "Position is " + getAdapterPosition(), Toast.LENGTH_SHORT).show(); return false; } }); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With