Android 更改导航视图片段

Android change fragment of navigation view

我有一个 Android 应用程序,其中包含 1 base activity 和一些片段。可以使用 DrawerLayout 中的 NavigationView 更改它们。用户可以在其中一个片段中更改应用程序的语言,当我重新启动应用程序时,我希望用户返回到该特定片段。

=====DrawerLayout=====
1. Fragment Home -> This is the starting fragment 
2. Fragment One
3. Fragment Settings -> Users change the language here. 

当用户更改语言时,会调用 base activity 中的一个方法,我会更改语言环境,然后调用 recreate()。这将刷新应用程序,并以新语言显示 Fragment Home。我想以编程方式更改为片段设置。

navigationView.<METHOD?>

为了解决您的问题,您可以保存特殊状态并重新创建activity。重新创建 activity 时,它将知道需要使用保存的状态移动到设置页面。

在您的 activity 中试试这个:

static final String SHOW_SETTINGS = "SHOW_SETTINGS";
private boolean showSettings = false;

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

    createLayoutAndDoOtherOnCreateThings();

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        if (savedInstanceState.getBoolean(SHOW_SETTINGS, false)) {
           showSettingsFragment();
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(SHOW_SETTINGS, showSettings);
    // Always call the superclass so it can save the view hierarchy state
   super.onSaveInstanceState(savedInstanceState);
}

private void callRecreateWithSettingsWhenRecreating() {
    showSettings = true;
    recreate();
}