You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在切换夜间模式时从SettingActivity重建MainActivity?

Solution for Reconstructing MainActivity After Night Mode Toggle

Hey there! I get exactly what you're dealing with—you toggle night mode in your SettingActivity, but when you head back to MainActivity, the layout doesn't update because onCreate() isn't triggered. Let's fix this with a few straightforward approaches:

Why this happens

When you call AppCompatDelegate.setDefaultNightMode(), the current activity (in this case, SettingActivity) will automatically recreate itself to apply the theme change. But your MainActivity is sitting in the background, so it doesn't get the memo to refresh. We need to manually tell it to rebuild.


Approach 1: Use Broadcasts to Trigger Recreate

This method sends a "heads-up" to MainActivity whenever the night mode changes, prompting it to rebuild.

  1. Register a Broadcast Receiver in MainActivity
    Add this code to your MainActivity to listen for the mode change broadcast:

    private BroadcastReceiver nightModeUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Rebuild the activity to apply new theme
            recreate();
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // Register the receiver with a custom action
        IntentFilter filter = new IntentFilter("com.yourapp.NIGHT_MODE_UPDATED");
        registerReceiver(nightModeUpdateReceiver, filter);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Don't forget to unregister to avoid memory leaks
        unregisterReceiver(nightModeUpdateReceiver);
    }
    
  2. Send Broadcast from SettingActivity
    After toggling the mode, send the broadcast before finishing the activity:

    // Toggle night mode using your ApplicationClass method
    ApplicationClass.setNightMode(); // or setDayMode()
    
    // Send broadcast to notify MainActivity
    Intent updateIntent = new Intent("com.yourapp.NIGHT_MODE_UPDATED");
    sendBroadcast(updateIntent);
    
    // Go back to MainActivity
    finish();
    

Approach 2: Use Activity Result API (AndroidX)

If you're using AndroidX, this is a cleaner alternative to startActivityForResult.

  1. Register Launcher in MainActivity
    When opening SettingActivity, use this launcher to listen for a result:

    private ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            // If we get a successful result, rebuild MainActivity
            if (result.getResultCode() == RESULT_OK) {
                recreate();
            }
        }
    );
    
    // Call this when you want to open SettingActivity
    public void openSettings() {
        settingsLauncher.launch(new Intent(this, SettingActivity.class));
    }
    
  2. Set Result in SettingActivity
    After toggling mode, set a result and finish:

    ApplicationClass.setNightMode(); // or setDayMode()
    setResult(RESULT_OK);
    finish();
    

Approach 3: Check Mode in onResume()

This simpler method checks if the night mode has changed every time MainActivity comes back to the foreground.

Add this to your MainActivity:

private int lastNightMode;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Save initial night mode state
    lastNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
}

@Override
protected void onResume() {
    super.onResume();
    // Check current night mode
    int currentNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
    
    // If mode changed, rebuild activity
    if (currentNightMode != lastNightMode) {
        lastNightMode = currentNightMode;
        recreate();
    }
}

All these methods will make sure MainActivity rebuilds and applies the new night mode theme. Your existing ApplicationClass code for setting night mode is totally correct—we just needed to trigger the refresh for the background activity.

内容的提问来源于stack exchange,提问作者Faisal Shaikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:22:56