在Android中运行时更改和应用主题

Gio*_*rgi 9 android themes android-theme android-activity

可能重复:
如何在Android中运行时更改当前主题

我有一个Android应用程序,我允许用户在运行时切换主题.切换主题很简单,但在重新创建活动之前不会应用主题.我找到了一种方法将主题应用于当前活动,但如果用户按下后退按钮,之前的屏幕仍然具有旧主题.如何更改这些活动的主题?支持它的应用程序示例:任务免费

She*_*tib 5

我想只是一个提示:

finish();通话前

setResult(AnIntegerThatNotifiesThePreviousActivitiesToChangeTheme);
Run Code Online (Sandbox Code Playgroud)

现在在您的所有活动中,实施 onActivityResult

protected void onActivityResult(int request, int result, Intent data) {
    if(result == AnIntegerThatNotifiesThePreviousActivitiesToChangeTheme)
    {
        //update the current theme
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个解决方案(更好):

实现一个保存主题的类:

public class CurrentThemeHolder {
    private CurrentThemeHolder() {
    }
    private static instance;
    public static getInstance() {
        if(instance == null)
            return new CurrentThemeHolder();
        else
            return instance;
    }
    private int mTheme; //identifier of the theme
    public getTheme() {
        return mTheme;
    }
    public setTheme(int newTheme){
        mTheme = newTheme;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在让你的所有活动扩展这个 ThemeActivity:

public class ThemeActivity extends Activity {
    private int mTheme;
    protected void onResume() {
        if(mTheme != CurrentThemeHolder.getInstance().getTheme()) {
            //do what you should do to set the theme
            mTheme = CurrentThemeHolder.getInstance().getTheme();
            //everytime you set the theme save it
            //this maybe should be done in onCreate()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Str*_*der 5

在运行时动态地,在调用setContentView()之前,在activity的onCreate()方法中调用setTheme().要更改主题,您只需重新启动活动即可.

请看这个文件..!

也想看到这个 ...希望这有助于......!

  • 这不回答这个问题.重新启动活动适用于当前显示的活动,但如何在用户点击时将其应用于其他活动? (4认同)
  • @Giorgi 使用 `starActivityForResult()` 从主要活动中调用次要活动。当次要活动返回时,自动调用主要活动的“onActivityResult()”方法。对于主题更改,您可以向主要活动返回一个“结果代码”,以便它知道它必须更改主题。如前所述,主题更改需要重新创建活动。至于后退按钮,覆盖次要活动的`onBackPressed()`方法,使其首先构建返回主活动的意图,然后调用`finish()`结束次要活动。 (2认同)