android - 是否可以在运行时设置工具栏的样式?

标签 android android-support-library android-toolbar android-theme

这是一个简短的问题:

我知道您可以通过 XML 创建具有指定主题的工具栏,例如 ( link ):

<android.support.v7.widget.Toolbar
    android:id="@+id/..."
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:title="@string/..."/>

在我的例子中,在运行时,应用程序可以有一些内容是白色或深色。

是否可以在运行时将(支持库的)工具栏的主题设置为具有特定主题?

是否至少可以将里面的项目设置为具有正确的选择器和项目色调颜色,以便按下它们仍然会有可见效果(将背景颜色更改为白色,当天黑时, 使效果不可见)?

最佳答案

据我所知,这是不可能的。

但是,我可以使用 ViewStub,当需要以正确的样式放置工具栏时,我可以这样做:

dark_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

light_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>

布局:

            <ViewStub
                android:id="@+id/..."
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"/>

代码:

    ViewStub viewStub = ...
    viewStub.setLayoutResource(...);
    final Toolbar toolbar = (Toolbar) viewStub.inflate();

如果我需要“更改工具栏的主题”,在它已经显示之后,我可以使用 2 个工具栏的 viewSwitcher(每个工具栏都有不同的主题),并且对于一个工具栏上的每个函数调用,为其他也是。当我需要在主题之间切换时,我可以在 viewSwitcher 中的 View 之间切换。

与切换主题不同,但仍然是一个不错的解决方法。

关于android - 是否可以在运行时设置工具栏的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280010/

相关文章:

android - Material 工具栏菜单背景填充和颜色

java - 尝试将工具栏包含到使用 NavDrawer 模板的应用程序中

android - list xml 文件中的多个 android.intent.action.MAIN

android - 如何在 "Add widget"对话框中对小部件进行分组

android - 从 android 联系人列表中获取电子邮件

android - 尝试更改文本颜色时 TabLayout.setTabTextColors() 不起作用

android - 停止使用 AppCompat

android - 自定义工具栏开头不需要的填充/边距

java - 方法中的字符串参数不起作用

java - Android - support.v7.PreferenceCategory 填满整个屏幕