Question

I have application with listview(one line contains textview, imageview, ratingbar) and my own adapter. When I rotate the screen after sorting listview (I choose this option in menu), it backs to form before sorting. I tried override onSaveInstanceState:

    @Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putParcelable("listView", listView.onSaveInstanceState());
}

and fragment onCreate:

         listView.setAdapter(adapter);

     if(savedInstanceState!=null)
     {
        mListInstanceState=savedInstanceState.getParcelable("listView");
        listView.onRestoreInstanceState(mListInstanceState);
     }

But it doesn't work. Should I override onRestoreInstanceState too or use something else?

Était-ce utile?

La solution

The problem is when orientation change your Activity is recreated and when onCreate() is called you are setting the adapter with the default list items.

If you don’t maintain different layout for landscape/portrait, you can simply avoid the Activity recreate by just adding configChanges in manifest for your Activity

       android:configChanges="orientation|screenSize"  // add this line

This will avoid recreating the Activity and same layout will be used to fit on screen width. Make sure your listView layout width is set to match_parent.

If you still want your Activity to recreate, then you need to remember the last selected filter when onSaveInstanceState is called on orientation change

  @Override
public void onSaveInstanceState(Bundle outState)= {
     outState.putString(“selectedFilter","some name");
    super.onSaveInstanceState(outState);
}

And then when onCreate in called after rotate, you can get the selectedFilter name

  String filterName = null;

    if(savedInstanceState != null){
        filterName = savedInstanceState.getString("lastFilter");
    }

Finally , set the listView with items based on the filter name.

 if(filterName != null && filterName.equalsIgnoreCase("some name")){
        // filtered list items
 } else {
         // default list items
   }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top