OnItemLongClick在RecyclerView中不起作用

时间:2015-10-26 07:23:11

标签: android android-recyclerview

我在使用RecyclerView时遇到问题,因为当我长按视图时,会产生简单的点击。这是长按的简单实现。当然,在我的代码中,我将这些监听器设置为我的适配器。

public class HomeListAdapter extends RecyclerView.Adapter<HomeListAdapter<P>.ViewHolder> {

    OnItemClickListener mItemClickListener;
    OnItemLongClickListener mItemLongClickListener;

    public HomeListAdapter() {
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {


        public ViewHolder(View itemView, int viewType) {
            super(itemView);
        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null) {
                mItemClickListener.onItemClick(itemView, getPosition());
            }
        }

        @Override
        public boolean onLongClick(View v) {
            if (mItemLongClickListener != null) {
                mItemLongClickListener.onItemLongClick(itemView, getPosition());
                return true;
            }
            return false;
        }
    }

        public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
            this.mItemClickListener = mItemClickListener;
        }

        public void setOnItemLongClickListener(final OnItemLongClickListener mItemLongClickListener) {
            this.mItemLongClickListener = mItemLongClickListener;
        }
    }


public interface OnItemClickListener {
    void onItemClick(View view, int position);
}

public interface OnItemLongClickListener {
    void onItemLongClick(View view, int position);
}


public class HomeListOnItemClickListener implements OnItemClickListener{

    @Override
    public void onItemClick(View view, int position) {
        Log.d("Test", "Click");
    }
}

public class HomeListOnItemLongClickListener implements OnItemLongClickListener{

    @Override
    public void onItemLongClick(View view, int position) {
        Log.d("Test", "Long Click");
    }
}

我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

itemView.setOnLongClickListener(new OnLongClickListener() 
 {
    @Override
    public boolean onLongClick(View v) {

     Toast.makeText(v.getContext(), "Long Click" ,Toast.LENGTH_SHORT).show();
     return true;

    }
 });

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html

  

public void setOnLongClickListener(View.OnLongClickListener l)

     

在API级别1中添加注册此视图时要调用的回调   点击并按住。如果此视图不能长时间点击,则会变为   长期可点击。