【问题标题】:Change and apply theme at runtime in Android [duplicate]在Android中在运行时更改和应用主题[重复]
【发布时间】:2012-07-10 20:15:23
【问题描述】:

可能重复:
How to change current Theme at runtime in Android

我有一个 Android 应用程序,允许用户在运行时在主题之间切换。切换主题很容易,但the theme isn't applied until the activity is recreated. 我找到了apply the theme to current activity 的方法,但如果用户按下后退按钮,以前的屏幕仍然有旧主题。如何更改这些活动的主题?支持它的应用示例:Tasks Free

【问题讨论】:

    标签: android themes android-activity android-theme


    【解决方案1】:

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

    请看this file..!

    还想看thisthis ... 希望这会有所帮助...!

    【讨论】:

    • 重新启动活动适用于当前活动,但当用户单击后退按钮时,以前的活动仍然具有旧主题。这是因为当用户返回时不会调用 onCreate,所以我无法设置主题。
    • 您想将主题设置为永久,然后像动态壁纸一样制作一个应用程序,然后在设置中您可以添加不同的样式..! @Giorgi
    • 这没有回答问题。重新启动活动适用于当前显示的活动,但是当用户点击返回时如何将其应用到其他活动?
    • @Giorgi 使用starActivityForResult() 从主要活动中调用次要活动。当次要活动返回时,自动调用主要活动的onActivityResult() 方法。对于主题更改,您可以向主活动返回一个“结果代码”,以便它知道它必须更改主题。如前所述,主题更改需要重新创建活动。至于返回按钮,重写辅助Activity的onBackPressed()方法,使其先构建返回主Activity的intent,然后调用finish()结束辅助Activity。
    【解决方案2】:

    我想只是一个提示:

    finish(); 致电之前

    setResult(AnIntegerThatNotifiesThePreviousActivitiesToChangeTheme);
    

    现在在你的所有活动中,实现 onActivityResult

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

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

    实现一个保存主题的类:

    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;
        }
    }
    

    现在让你所有的活动扩展这个 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()
            }
        }
    }
    

    【讨论】:

    • 你好,谢里夫,我想知道是否有任何解决方案可以让我从网络获取颜色代码,并据此更改所有按钮运行时的颜色,而无需转到所有特定按钮并应用背景颜色,有没有使用主题或样式的解决方案?请分享您的任何建议。
    • 你有无限的颜色吗?还是只是一组有限的颜色?
    • 我确实限制了 20 种颜色,但是这 20 种是从服务器下载的,所以它可能会因时间而异,总之颜色大约是 15-20(不固定)和那些颜色代码也没有修复。其中一位用户建议使用 CustomViews stackoverflow.com/questions/22529646/…
    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多