Is it possible to refresh the view of a Fragment

2019-02-05 20:10发布

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

3条回答
你好瞎i
2楼-- · 2019-02-05 20:22

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!

查看更多
Animai°情兽
3楼-- · 2019-02-05 20:27

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

查看更多
姐就是有狂的资本
4楼-- · 2019-02-05 20:30

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.

查看更多
登录 后发表回答