在运行时更改区域设置时刷新(重新创建)后台堆栈中的活动

Pra*_*eth 9 android recreate onresume

我有一个活动说ActivityMain从这个活动我移动到另一个名为的活动ActivitySettings,在设置活动中我通过单击按钮更改应用程序区域设置,并使用重新创建我实现了我在当前活动中需要的更改但是当我按下我的` ActivityMain' 将恢复,但区域设置不会更新。

有人可以告诉我如何“重新创建”backstack 活动吗?什么是正确的方法。

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

Sag*_*gar 4

在每个活动中,onCreate()您可以维护currentLangCode. 检查此值onResume(),如果不同,您可以断定区域设置已更改,并且recreate()

您可以按如下方式进行操作:

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();
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的推荐

如果你想将它应用于所有的Activity,那么只需创建BaseActivity,如下所示:

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();
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

将所有活动从BaseActivity

public class ActivityA extends BaseActivity{

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }
    @Override
    public void onResume(){
      super.onResume();
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)