如何在单击时在运行时为整个应用程序设置自定义主题?

时间:2018-11-03 08:50:17

标签: android

如何在不调用活动的情况下更改主题?

假设我有两个活动A和B。我从活动A调用活动B。从活动B我更改主题,并通过执行recreate()更改活动B的主题。但是,如何更改活动A的主题(位于后排堆栈中)?

我不想从活动B撤回活动A。

1 个答案:

答案 0 :(得分:0)

这里的问题是当您从Activity B返回到Activity A时,这最后一个将恢复。因此,在onResume方法中,您需要检查主题是否已更改,并将其应用于您的活动。

以下是示例:

public class BaseActivity extends AppCompatActivity {

    private int mTheme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mTheme = getCurrentTheme();
        setTheme(mTheme);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();

        int currentTheme = getCurrentTheme();

        // If the theme has changed, we need to apply it
        if (mTheme != currentTheme) {
            // Recreate activity
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
    }
}
相关问题