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

后端 未结 20 1683
無奈伤痛
無奈伤痛 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条回答
  • 2020-11-21 22:22

    I adopted the solution suggested by @(Kirk Woll), and it works for me. I have also seen in the Android source code for the "Contacts" app, that they use a similar technique. I would like to add some more details: On top on my ListActivity-derived class:

    private static final String LIST_STATE = "listState";
    private Parcelable mListState = null;
    

    Then, some method overrides:

    @Override
    protected void onRestoreInstanceState(Bundle state) {
        super.onRestoreInstanceState(state);
        mListState = state.getParcelable(LIST_STATE);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        loadData();
        if (mListState != null)
            getListView().onRestoreInstanceState(mListState);
        mListState = null;
    }
    
    @Override
    protected void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        mListState = getListView().onSaveInstanceState();
        state.putParcelable(LIST_STATE, mListState);
    }
    

    Of course "loadData" is my function to retrieve data from the DB and put it onto the list.

    On my Froyo device, this works both when you change the phone orientation, and when you edit an item and go back to the list.

    0 讨论(0)
  • 2020-11-21 22:22

    Isn't simply android:saveEnabled="true" in the ListView xml declaration enough?

    0 讨论(0)
提交回复
热议问题