【问题标题】:How to setTheme to dark on one Button如何在一个按钮上将主题设置为暗
【发布时间】:2018-02-22 02:37:53
【问题描述】:

可以通过一键从 ThemeUtils 设置主题?查看屏幕截图只需一个按钮“反转”即可将 Light 设置为 Dark 并将 Dark 设置为 Light ?如果可能的话怎么做?请帮助我

我的代码:

case R.id.Invert:
            ThemeUtils.setTheme(this, "dark");
            return true;

看这张图片:https://drive.google.com/file/d/0B5SpWSpauPDuSGtWREgybnB6aEk/view?usp=drivesdk

【问题讨论】:

    标签: java android xml material-design toolbar


    【解决方案1】:

    你必须在调用SetContentView之前调用Activity上的setTheme方法

    因此要更改已打开的Activity 的主题,您需要重新启动它。

    例如:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(YOUR_THEME_FROM_SHARED_PREFS);
        setContentView(...)
    }
    

    case R.id.Invert:
                // Set theme in shared Prefs here
    
                this.recreate(); // restart the activity
                return true;
    

    【讨论】:

    • 我的意思是在一个按钮上可以设置两个主题,1.如果当前主题为白色,则将 Light 设置为黑色,2.如果当前主题为黑色,则按钮将 setTheme 为 Light ??我在 2 个按钮上创建了主题,我只想要一个按钮,比如“反转”颜色
    • 没有。你必须像我的回答解释的那样去做。您无法更改已打开的 Activity 的主题。
    • 您可以使用按钮选择主题(这就是您将其保存到共享首选项的原因),但您仍然需要重新启动 Activity 才能使其生效
    • 在特定的视图上,它不是一个主题,而是一种风格。主题适用于整个活动或更大的一组视图。
    • 他不是在问如何改变一个按钮的样式。他在问如何使用一个按钮在深色和浅色之间切换主题,而不是使用单独的按钮。
    【解决方案2】:

    是的,当然。定义主题,您要设置在style 文件夹中。而不是你的字符串写代码R.style.YourOwnTheme

    【讨论】:

    • 我已经做了一个主题。但我想通过当前主题更改主题,如果(当前主题 == Light){ setTheme(dark); } else if (current theme == dark){ set Theme(light); } 像这样
    • @WahyuHidayat 您可以通过代码获取主题:this.getTheme().getResourseId() 然后通过 this.getTheme().getResourseId() == R.style.YourTheme 进行检查
    • @WahyuHidayat 之后别忘了重启活动
    • 我把代码放在哪里了?? this.getTheme().getReourcesId() ??在 MainActivity 或 ThemeUtils 上? @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home:drawerLayout.openDrawer(GravityCompat.START);返回真; case R.id.Invert: ThemeUtils.setTheme(this, "Light");返回真; } 返回 super.onOptionsItemSelected(item); }
    • @WahyuHidayat 在你的 if 语句中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2015-05-27
    • 2016-07-23
    • 1970-01-01
    • 2021-03-26
    相关资源
    最近更新 更多