Is it possible to refresh the view of a Fragment

2019-02-05 20:03发布

问题:

I changed the locale of my application programmatically, like following:

Resources res = context.getResources();

 DisplayMetrics dm = res.getDisplayMetrics();
 android.content.res.Configuration conf = res.getConfiguration();
 conf.locale = new Locale("cn");
 res.updateConfiguration(conf, dm);

After this, I would like to refresh my currently displayed fragment's view to display with new locale settings.

So, I firstly get the current fragment (that's the latest one in backstack):

BackStackEntry latestEntry=fragMgr.getBackStackEntryAt(fragMgr.getBackStackEntryCount()-1);
String str=latestEntry.getName();
Fragment fragment=fragMgr.findFragmentByTag(str);

After I get the currently showing fragment, I would like to refresh its view, but how to do it? Is it possible in Android to refresh the view of a fragment

回答1:

You can simply detach and attach fragment as below

    Fragment currentFragment = getFragmentManager().findFragmentByTag("FRAGMENT");
    FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
    fragTransaction.detach(currentFragment);
    fragTransaction.attach(currentFragment);
    fragTransaction.commit();

This will refresh the view and locale will change



回答2:

You could create a listener, which will be called when the locale changes. This will then remove the Fragment, and re add the Fragment. Your new locale should then be picked up.



回答3:

I finally found the solution to it! Just run your view update code in the UI thread

Example -

 getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                user_arrayList.add(name);
                adapter.notifyDataSetChanged();
                tv_total_users.setText("Total Users : "+user_arrayList.size());
            }
        });

Finally found this solution after trying for almost 4-5 hours!