Android: Refresh current fragment after language c

2019-09-10 14:33发布

问题:

So my MainActivity has a navigation drawer with a set of fragments.

On top of the nav bar, I have 2 flags which represent a language. If an user clicks on a language, the app changes the language of the whole app.

Everything is working smoothly (activity refreshes, navigation drawer and all fragments get translated) but the fragment that's open doesn't. This means that the user needs to click on the navigation drawer and select the fragment again to see it translated.

How can I refresh the current fragment the user is in?

回答1:

Add tag to your fragment when you commit it:

fragmentManager.beginTransaction().replace(R.id.your_id, fragment, "Your_Fragment_TAG").commitAllowingStateLoss();

Then You can detach and attach again your fragment for refresh:

// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();