gpt4 book ai didi

java - 根据 RecyclerView 中的 Scroll 事件更改方向

转载 作者:行者123 更新时间:2023-11-30 10:22:56 25 4
gpt4 key购买 nike

我正在尝试根据用户向上/向下滚动或向左/向右滚动操作来更改 recyclerview 的方向。这是我的 onCreate() 方法:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setAdapter(new MyAdapter(totalItemCount));

// default orientation is VERTICAL
gridLayoutManager = new GridLayoutManager(this, spanCount, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(gridLayoutManager);

RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.i("TAG", "current orientation: " + gridLayoutManager.getOrientation());

if (dx > 0) {
Log.i("TAG", "dx = " + dx);
recyclerView.post(new Runnable() {
@Override
public void run() {
gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
}
});

} else if (dy > 0) {
Log.i("TAG", "dy = " + dy);
recyclerView.post(new Runnable() {
@Override
public void run() {
gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
}
});
}
recyclerView.setLayoutManager(gridLayoutManager);
}
};

recyclerView.addOnScrollListener(listener);
}

问题是它不会改变 recyclerview 中的方向。改变方向是正确的方法吗?

编辑

建议的代码修改后没有异常(@RobCo)。但我仍然不能改变方向。

最佳答案

错误信息很清楚:

Cannot call this method in a scroll callback. Scroll callbacks might be run during a measure & layout pass where you cannot change theRecyclerView data. Any method call that might change the structure of the RecyclerView or the adapter contents should be postponed to the next frame.

因此,setOrientation 不能从布局或测量过程中调用,也不能在滚动回调期间调用。您必须将 Runnable 发布到下一帧:

    recyclerView.post(new Runnable() {
@Override
public void run() {
gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
}
});

关于java - 根据 RecyclerView 中的 Scroll 事件更改方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47306566/

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