Maintain/Save/Restore scroll position when returning to a ListView

后端 未结 20 1713
無奈伤痛
無奈伤痛 2020-11-21 21:30

I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the

20条回答
  •  猫巷女王i
    2020-11-21 22:09

    Parcelable state;
    
    @Override
    public void onPause() {    
        // Save ListView state @ onPause
        Log.d(TAG, "saving listview state");
        state = listView.onSaveInstanceState();
        super.onPause();
    }
    ...
    
    @Override
    public void onViewCreated(final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // Set new items
        listView.setAdapter(adapter);
        ...
        // Restore previous state (including selected item index and scroll position)
        if(state != null) {
            Log.d(TAG, "trying to restore listview state");
            listView.onRestoreInstanceState(state);
        }
    }
    

提交回复
热议问题