Handle on item long click on recycler view

Marco Di Munno picture Marco Di Munno · May 6, 2015 · Viewed 67.4k times · Source

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?

Answer

Albert Vila Calvo picture Albert Vila Calvo · Nov 11, 2015

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
    }
}