以编程方式更改AppBarLayout主题

8

首先,我通过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>

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

我尝试了这两种方法,但没有成功:

  1. 第一步:

    ActionBar actionBar = getSupportActionBar();
    actionBar.getThemedContext().setTheme(R.style.MyTheme_AppBarOverlay_2);
    
  2. 第二步:

    AppBarLayout mAppBar = (AppBarLayout) findViewById(R.id.appbar);
    mAppBar.getContext().setTheme(R.style.MyTheme_AppBarOverlay_2);
    

这个有成功了吗? - Pei
我还没有开始工作,所以目前没有任何消息。 - android iPhone
这个有什么进展吗? - Franco
1个回答

0

在 Android 视图中,通货膨胀后更改主题是不可能的。您必须逐个更改主题定义的每个属性。您可以通过使用 Compose TopAppBar 来解决此问题,因为 Compose 小部件会对主题更改做出反应。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接