【问题标题】:How to recreate activity from another activity when enable/disable Night mode?启用/禁用夜间模式时如何从另一个活动重新创建活动?
【发布时间】:2019-06-19 12:12:38
【问题描述】:

我发现了很多与此相关的问题,但我的问题有点不同。

在 SettingActivity 中,我通过以下代码启用/禁用夜间模式:

ApplicationClass.setNightMode();
ApplicationClass.setDayMode();

在应用程序类中编写的实际代码。

但是当我从 SettingActivity 返回到 MainActivity 时,布局的颜色不会因为 onCreate() 方法而改变。

当我启用/禁用夜间模式时,如何从 SettingActivity 重新创建 MainActivity。

我启用和禁用夜间模式的应用程序代码:

    public static void setNightMode(){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }

    public static void setDayMode(){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    }

【问题讨论】:

标签: android android-activity android-theme


【解决方案1】:

您的AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); 应位于应用程序级别。而且,当您返回或继续您的应用程序之间的任何活动时,这将不是问题。不要忘记将其注册到清单中。

例子:

public class TestApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //give a start value AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }

    public static void setNightMode(){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }

    public static void setDayModeOrSth(){
        //AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }
}

在你的清单文件中:

<application
            android:name="package.name.TestApplication"

比你的活动/片段

Testapplication.setDayModeOrSth();

Testapplication.setNightMode();

请原谅我愚蠢的命名和示例 :) 但它会是这样的。祝你好运。

【讨论】:

  • 能否分享或举个例子?
  • 我试过你的代码,但没有用。我用代码更新了问题。你可以看看。
  • 在您的onResume 中放置:AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.getDefaultNightMode())
  • 在 MainActivity onResume() 中添加了如下代码,但还是不行AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.getDefaultNightMode());
  • 我不知道。
【解决方案2】:

如果您重新创建 MainActivity,您将失去它的当前状态,因此您可以尝试覆盖 onResume 并检查您是否需要启用/禁用夜间模式:

public class MainAcitivy extends ... {

    .....

    @Override
    public void onResume(){
        super.onResume();
        if(nightModeOn) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }
}

另一种解决方案是通过覆盖SettingActivity中的onBackPressed来启动一个新的MainActivity并启动MainActivity:

public class SettingsActivity extends .. {

    .....

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finishAffinity();
    }

}

【讨论】:

    【解决方案3】:

    您可以覆盖活动的 onConfigurationChanged 方法。

    public abstract void onConfigurationChanged (Configuration newConfig)

    【讨论】:

    • 您不需要重新创建活动。只需实现 onConfigurationChanged 方法,只要配置发生变化,控制就会自动转移到那里
    • 你能分享一下这方面的任何例子吗?
    猜你喜欢
    • 2015-11-25
    • 2020-12-31
    • 1970-01-01
    • 2011-01-18
    • 2015-07-22
    • 1970-01-01
    • 2018-06-19
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多