如何更改RecyclerView的方向?

时间:2015-11-24 09:41:18

标签: android orientation gridlayoutmanager

我像这样使用了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的方向?

1 个答案:

答案 0 :(得分:1)

为什么要将listner设置为Adapter,在recyclelerview上设置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);
            }
        })
);