android - 以编程方式更改 AppBarLayout 主题

标签 android android-actionbar android-toolbar android-appbarlayout

首先我通过 xml 设置 AppBarLayout 主题:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MyTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/MyTheme.PopupOverlay"
        app:titleTextAppearance="@style/MyTheme.Toolbar.Title" />

在哪里 @style/MyTheme.AppBarOverlay 包含:
<style name="MyTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="colorPrimary">@drawable/toolbar_background</item>
</style>

但是在某些情况下,我想以编程方式更改它而不更改 Activity 的主题(仅 AppBarLayout 的主题)。

我试过这两种方法都没有成功:
  • 第一的:
    ActionBar actionBar = getSupportActionBar(); actionBar.getThemedContext().setTheme(R.style.MyTheme_AppBarOverlay_2);
  • 第二:
    AppBarLayout mAppBar = (AppBarLayout) findViewById(R.id.appbar); mAppBar.getContext().setTheme(R.style.MyTheme_AppBarOverlay_2);
  • 最佳答案

    Android View 无法在通货膨胀后更改主题。您必须更改主题单独定义的每个属性。您可以使用 Compose TopAppBar 解决此问题。 ,因为 Compose 小部件会对主题更改使用react。

    关于android - 以编程方式更改 AppBarLayout 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786418/

    相关文章:

    android-layout - 像谷歌游戏商店一样折叠工具栏布局

    java - onCompleted 方法

    运行 Maven Android 项目时 AndroidManifest.xml 文件丢失错误

    android - 如何在android中以百分比获取触摸位置

    android - ActionBar 上的动态 TextView

    Android:RTL ActionBar 菜单项

    android - ActionBar - 具有居中 ImageView 的自定义 View ,两侧的操作项

    android - 添加图标到工具栏Android

    android - html5 视频标签中的 Mp4 视频无法在移动 chrome 和移动 safari 中播放

    android - CollapsingToolbarLayout 内的工具栏,工具栏标题不显示