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

时间:2017-11-15 11:44:56

标签: java android android-recyclerview

我正在尝试根据用户的向上/向下滚动或向左/向右动作更改recyclelerview的方向。这是我的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)没有异常。但我还是无法改变方向。

1 个答案:

答案 0 :(得分:1)

错误信息非常明确:

  

无法在滚动回调中调用此方法。在测量和测量过程中可能会运行滚动回调。布局传递,您无法更改RecyclerView数据。任何可能改变RecyclerView结构或适配器内容的方法调用都应推迟到下一帧。

因此,无法从布局或度量传递或滚动回调期间调用setOrientation。你必须将Runnable发布到下一帧:

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