首页 > 解决方案 > 使用 Recycler View 将房间数据库滚动到特定位置

问题描述

我正在使用 Room 数据库从数据库中获取数据。Recyclerview 我想滚动到recyclerview 中的特定位置。

我已经尝试过 list.setNestedScrollingEnabled(true)

StationListRepository stationListRepositoryOnlyActive = new StationListRepository(getApplicationContext()); stationListRepositoryOnlyActive.getActiveStationList().observe(this, new Observer>() { @Override public void onChanged(List OnlyActivestations) { Log.d("OnlyActivestations", "" + OnlyActivestations.size()); assert OnlyActivestations != null; if (OnlyActivestations.size() > 0 || FinalList.size() > 0) { if (FinalList != null && FinalList.size() > 0) { OnlyActivestations = sortList(OnlyActivestations); FinalList.addAll(OnlyActivestations);

                } else {
                    OnlyActivestations = sortList(OnlyActivestations);
                    FinalList = OnlyActivestations;
                }
                Log.d("FinalListSizeActive",""+FinalList.size());
                detailsAdapter = new db_stationListAdapter(context, FinalList);
                //recyclerView.setNestedScrollingEnabled(true);
                StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
                staggeredGridLayoutManager.scrollToPosition(10);
                recyclerView.setLayoutManager(staggeredGridLayoutManager);
                recyclerView.setAdapter(detailsAdapter);
                detailsAdapter.notifyDataSetChanged();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       // stopLoading();
                        stopAnimation();
                    }
                });
            }
        }
    });

我除了回收站视图自动滚动到位置 10

标签: androidandroid-recyclerviewandroid-room

解决方案


将数据设置到适配器后尝试使用下面的代码

recyclerView.smoothScrollToPosition(10);

或者

您可以将OnLayoutChangeListener添加到 RecyclerView。

recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener(){

        @Override
        public void onLayoutChange(View v, int left, int top, int 
             right, int bottom, int oldLeft, int oldTop, int oldRight, 
                         int oldBottom) {

            if (bottom < oldBottom) {

                   recyclerView.postDelayed(new Runnable() {

                    @Override
                    public void run() {


                            recyclerView.smoothScrollToPosition(10);


                    }
                }, 100);
            }
        }
    });

推荐阅读