recyclerview的findFirstVisibleItemPosition()始终返回-1

时间:2016-02-21 19:05:29

标签: android android-recyclerview

这是我希望在方向更改和活动恢复时保留recyclerview的滚动位置的代码。问题出在我的日志中,我总是得到-1。我哪里错了?

$this->getDI()->getShared('config');

1 个答案:

答案 0 :(得分:1)

一切都非常简单,因为你重载适配器,LayoutManager没有时间在自身内部构建元素,这意味着此时所有元素都在屏幕上不可见。如果您甚至尝试拨打recyclerView.getChildCount(),则会获得0

尝试这样的事情:

recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
new Handler().postDelayed(new Runnable(){
        public void run() {
            RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
            if (lm != null && lm instanceof LinearLayoutManager) {
                currPosition = ((LinearLayoutManager)lm).findFirstVisibleItemPosition();
                Log.i("saz","curr pos : " + currPosition);
            }
            int count = lm.getChildCount();
            if (currPosition != RecyclerView.NO_POSITION && currPosition < count){
                lm.scrollToPosition(currPosition);
            }
        }
    }, 500);