在另一个视图中获取RecycleView详细信息的最佳方法

时间:2017-07-26 09:07:40

标签: android android-recyclerview

我正在我的主布局上实现onClick,其中包含我的所有视图,以便将数据传递到另一个视图,例如:

 holder.wholeView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(mContext, String.valueOf(position), Toast.LENGTH_SHORT).show();
         //pass data with something like eventBus and transition to another view 
        }
    });

我认为有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

使用此:

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

}

从您使用Recycler视图的活动中,您可以像这样使用它:

mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, mRecyclerView,
                new RecyclerTouchListener.ClickListener() {
                    @Override
                    public void onClick(View view, int position) {
                    // use this position to fetch the data from your list which you used to populate your recylcer view
                    }

                    @Override
                    public void onLongClick(View view, int position) {

                    }
                }));

答案 1 :(得分:0)

您应该拥有制作回收者查看项目的项目列表。现在只需使用此

myList.get(holder.getAdapterPosition());

这将返回点击位置的对象。

希望这有帮助。