2

我像这样使用 RecyclerView,

mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);

mLayoutManager = new GridLayoutManager(getActivity(), 2, LinearLayoutManager.VERTICAL, false);

mRecyclerView.setLayoutManager(mLayoutManager);

mAdapter = new GridAdapter((getActivity()), getGridItems());
mAdapter.setOnItemClickListener(new GridAdapter.OnItemClickListener() {

        @Override
        public void onItemClick(View itemView, int position) {
            Toast.makeText(getContext(), getGridItems().get(position).mtitle, Toast.LENGTH_SHORT).show();
        }
});

如您所见,RecycleView 具有 GridLayoutManager。但是当我调用 Toast 2nd 时,第 3 项的标题相互更改。

我认为 RecycleView 的方向是问题。

如何设置 ReecycleView 的方向?

4

1 回答 1

1

为什么要将listner设置为适配器,在recyclerview本身上设置listner,首先使用这个类:

        import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    import android.view.View;

       public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    private OnItemClickListener mListener;
    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }
    GestureDetector mGestureDetector;
    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }
    @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.getChildAdapterPosition(childView));
        }
        return false;
    }

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

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

      }
    }

然后你可以像这样使用它:

   recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new   RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                // TODO Handle item click
                Log.e("Position = ",""+position);
            }
        })
);
于 2015-11-24T09:50:54.513 回答