gpt4 book ai didi

android - 如何更改 RecyclerView 的方向?

转载 作者:行者123 更新时间:2023-11-30 01:44:47 25 4
gpt4 key购买 nike

我是这样使用 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 时,第三项的标题会相互更改。

我认为 RecycleView 的方向有问题。

如何设置 ReecycleView 的方向?

最佳答案

为什么要将监听器设置到适配器,将监听器设置到 recyclerview 本身,首先使用此类:

        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);
}
})
);

关于android - 如何更改 RecyclerView 的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33890119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com