在运行时更改语言环境时刷新(重新创建)后退堆栈中的活动 [英] Refresh(recreate) the activities in back stack when change locale at run time

查看:53
本文介绍了在运行时更改语言环境时刷新(重新创建)后退堆栈中的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动说 ActivityMain ,该活动已移至另一个名为 ActivitySettings 的活动,并且在设置活动中,我通过单击按钮来更改应用程序的语言环境,并使用recreate实现了当前活动中所需的更改,但是当我按回我的"ActivityMain"时,它将恢复,但语言环境未更新.

I have an Activity say ActivityMain from this activity I moved to another activity called ActivitySettings and in settings activity I'm changing the App locale by clicking on a button, and using recreate I achieved the change I need in current activity but when I press back my `ActivityMain' will resume but locale is not updated.

有人可以告诉我如何重新创建"堆栈活动吗?什么是正确的方法.

Can some one tell me how to 'Recreate' backstack activities? what will be the correct approach.

我无法在刷新时调用recreate,因为它将是无限循环

I can't call recreate on refresh as it will be infinite loop

推荐答案

在每个活动的 onCreate()中,您可以维护 currentLangCode .在 onResume()中检查此值,如果不同,则可以推断出语言环境已更改,并且可以得出 recreate()

In each Activity's onCreate() you can maintain the currentLangCode. Check this value in onResume(), if it differs, you can conclude the locale was change and recreate()

您可以按照以下步骤进行操作:

You can do it as follows:

public class ActivityA extends AppCompatActivity{
    private String currentLangCode;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        currentLangCode = getResources().getConfiguration().locale.getLanguage();
        ...
    }
    @Override
    public void onResume(){
        ...
        if(!currentLangCode.equals(getResources().getConfiguration().locale.getLanguage())){
            currentLangCode = getResources().getConfiguration().locale.getLanguage();
            recreate();
        }
    }
    ...
}

我的推荐

如果要将其应用于所有活动,则只需按如下所示创建BaseActivity:

My Recommendation

If you want to apply it for all the Activities, then simply create BaseActivity as follows:

public class BaseActivity extends AppCompatActivity{
    private String currentLangCode;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        currentLangCode = getResources().getConfiguration().locale.getLanguage();
        ...
    }
    @Override
    public void onResume(){
        ...
        if(!currentLangCode.equals(getResources().getConfiguration().locale.getLanguage();)){
            currentLangCode = getResources().getConfiguration().locale.getLanguage();
            recreate();
        }
    }
    ...
}

BaseActivity

public class ActivityA extends BaseActivity{

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }
    @Override
    public void onResume(){
      super.onResume();
    }
    ...
}

这篇关于在运行时更改语言环境时刷新(重新创建)后退堆栈中的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆