itemclick android中的recyclerview监听器

时间:2016-06-01 09:07:22

标签: android

我正在使用带有cardview的android recyclerview,它使用来自服务器的数据填充。我想为每个项目设置itemclick事件,并且需要显示带有文本的对话框。这个文本也来自服务器。对于不同的项目会有所不同。

当我尝试给予时,

 mItem=lists.getRemarks();
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SweetAlertDialog(v.getContext())
                    .setTitleText("Remark")
                    .setContentText(mItem)
                    .show();
        }
    });

它只提供最后的细节

2 个答案:

答案 0 :(得分:1)

不知怎的,我通过将 setContentText(mItem)设置为 setContentText(lists.getRemarks())来解决它

答案 1 :(得分:1)

Recyclerview没有项目点击监听器,所以我有一个custom class来检测它

<强> RecyclerItemClickListner

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener
{
    public static interface OnItemClickListener
    {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
    {
        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
        {
            @Override
            public boolean onSingleTapUp(MotionEvent e)
            {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
    {
        View childView = view.findChildViewUnder(e.getX(), e.getY());

        if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
        {
            mListener.onItemClick(childView, view.getChildPosition(childView));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

使用

 mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
               // do whatever you want on position clicked 
            }

            @Override
            public void onItemLongClick(View view, int position) {
              // do whatever you want on position long press
            }
        }));