Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

android - Handle on item long click on recycler view

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?

question from:https://stackoverflow.com/questions/30078344/handle-on-item-long-click-on-recycler-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...