【问题标题】:Room database scroll to a particular position using Recycler View使用 Recycler View 将房间数据库滚动到特定位置
【发布时间】:2019-11-01 03:10:12
【问题描述】:

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

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

StationListRepository stationListRepositoryOnlyActive = new StationListRepository(getApplicationContext()); stationListRepositoryOnlyActive.getActiveStationList().observe(this, new Observer>() { @覆盖 public void onChanged(List OnlyActivestations) { Log.d("OnlyActivestations", "" + OnlyActivestations.size()); 断言 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

【问题讨论】:

    标签: android android-recyclerview android-room


    【解决方案1】:

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

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

    【讨论】:

    • 你的第二个解决方案对我有用,我真的很感谢你。
    猜你喜欢
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2015-10-18
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多