这是一个简短的问题:
我知道您可以通过 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/