Matt M
Matt M

Reputation: 3779

Empty list after orientation change

First off, I've already looked at this question. In my scenario, I have a fragment that extends support.v4.app.ListFragment. The fragment calls a custom adapter. I need to handle orientation changes on a device that will switch to a 2 pane layout. I believe I'm doing most things right as the view itself changes correctly and I am able to retrieve the data from savedInstanceState. However, my list is always empty. I tried the recommended answer in the linked question (calling setListShown(true)), but I get an exception, "Can't be used with a custom content view". The relevant code is below:

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    ViewGroup group = ((ViewGroup) getView());
    group.removeAllViews();
    inflater.inflate(R.layout.activity_message_list, group);  
    if(!messages.isEmpty()){
        mAdapter = new MessageListAdapter(getActivity().getApplicationContext(), messages);
    }
    setListAdapter(mAdapter); 
}

The adapter's getView method is never invoked after the configuration change. What else do I need to do to re-hydrate the view? Let me know if you need to see any other code.

Upvotes: 0

Views: 916

Answers (3)

Matt M
Matt M

Reputation: 3779

With a ton of direction from Chaosit, I was able to achieve what I wanted. My app has a nav drawer activity and I swap the fragment (which is a master-detail type fragment) based on the selection. I added android:configChanges="orientation" so the fragment wouldn't revert back to the default selection I made in the onCreate method of the activity. So, I removed that line and made the adjustments to store the selection in the savedInstanceState bundle. Everything is working as I would have expected now.

Upvotes: 0

alexscmar
alexscmar

Reputation: 421

There is a way to avoid app reload after device orientation changed, you just have to tell system that you'll handle screen orientation changed events on your own. Have you tried to add parameter android:configChanges="orientation" inside activity tag in Manifest.xml?

Upvotes: 0

Chaosit
Chaosit

Reputation: 1116

Since you are creating a new view then you have to redo all View's initialization that you do in the original piece of code (in onViewCreated or somewhere else). So, in order to initialize the ListView - you should do something like this:

View rootView = inflater.inflate(R.layout.activity_message_list, group);  
if(!messages.isEmpty()){
    mAdapter = new MessageListAdapter(getActivity().getApplicationContext(), messages);
}
ListView listView = (ListView) root.findViewById(R.id.<your_list_view_id>;
listView.setAdapter(mAdapter);

Just keep in mind that you also have to do all other initialization (creating references to Views and creating onClickListeners or whatever else you're doing)

Upvotes: 1

Related Questions