Android: How to update Actionbar and Drawerlayout title and items at runtime?

Asked

Viewed 1,916 times

0

I need to update the Actionbar title and each of the Drawer menu items with the runtime language change. I use the following code to change the language of my application but I cannot change the title and items of actionbar (their names). I’ve tried using the supportInvalidateOptionsMenu() and it didn’t work. I’m using the Support Library. The other items are updated only the Actionbar and Drawer other than.

Fragment currentFragment = getFragmentManager().findFragmentById(getId());
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
  • You could include the layout for your Drawer menu and the Activity layout?

1 answer

1


I’ll guess you use the DrawerLayout of Support Library v4 and ActionBar from Support Library v7, but I have two suggestions to solve this problem:

Simple mode: restart the Activity, believing that the Strings that you use in the Drawer and in the ActionBar come right soon after, this can be done as follows:

    if (Build.VERSION.SDK_INT < 11) {
        Intent intent = activity.getIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

        activity.finish();
        activity.overridePendingTransition(0, 0);
        activity.startActivity(intent);
    } else {
        activity.recreate();
    }

This mode is the easiest, however there is the risk of data loss and has all the overhead of recreating the Activity.

The other way, maybe better depending on the case is to recover the ListView of DrawerLayout and use the method notifyDataSetChanged or notifyDataSetInvalidated in the Adapter, forcing the update of menu items. And ActionBar, just update the title.

Actionbar can be updated this way:

ActionBar ab = getSupportActionBar();

ab.setTitle(...); // Setar o title novamente, com a lingua correta.

Already the Drawer, you need to keep a reference in your Activity or retrieve it from ListView, being so:

// Se ja tiver a referência, não precisa fazer isso..
ListView lv = findViewById(R.id.drawer_list); // resId do ListView
ListAdapter adapter = lv.getAdapter();

adapter.notifyDataSetInvalidate();
// ou dependendo da necessidade
adapter.notifyDataSetChanged();
  • Thank you very much friend! It worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.