Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix Navigation Drawer Title change on orientation change?

When the orientation is changed on my app, the title in the action bar changes from the title of the fragment selected in the nav drawer to the title of the app.

The Navigation drawer example app retains it's title on orientation change because it's fragment is a subclass of the main activity, and has this line of code

getActivity().setTitle(planet);

Now i'm bit a newbie so i wouldn't know how to retain the title, and implement the code, can you guys help?

Just in case any of you wanna see, here is the subclass for the PlanetFragment

public static class PlanetFragment extends Fragment {
    public static final String ARG_PLANET_NUMBER = "planet_number";

    public PlanetFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
        int i = getArguments().getInt(ARG_PLANET_NUMBER);
        String planet = getResources().getStringArray(R.array.planets_array)[i];

        int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                        "drawable", getActivity().getPackageName());
        ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
        getActivity().setTitle(planet);
        return rootView;
    }
}
like image 592
Alex Avatar asked Dec 15 '22 08:12

Alex


1 Answers

From the Navigation drawer example app, here what I did :

  • On onSaveInstanceState() of your Activity :

    @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); CharSequence title = mDrawerLayout.isDrawerOpen(mLeftDrawer) ? mDrawerTitle:mTitle; outState.putCharSequence(KEY_STATE_TITLE, title); }

  • On onCreate() of your Activity:

    if (saveInstanceState!=null) { setTitle(savedInstanceState.getCharSequence(KEY_STATE_TITLE)); }

Hope this help.

like image 172
maohieng Avatar answered Jan 13 '23 14:01

maohieng