首页 > 解决方案 > 如何以编程方式为工具栏内的所有图标设置 colorControlHighlight (波纹颜色)?

问题描述

我知道有一种方法可以将主题设置为 xml 中的工具栏,如下所示:

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:theme="@style/ToolBarTheme"/>

和风格:

<style name="ToolBarTheme">
            <item name="android:colorControlHighlight">@color/white</item>
        </style>

但是有没有办法以编程方式设置它或使用专门用于工具栏的主应用程序主题,而不仅仅是覆盖主主题中的 colorControlHighlight (因为它也会影响其他视图)?

标签: android

解决方案


找到了适合我的解决方案。我有一个扩展 Toolbar 类的 CustomToolbar 类。在构造函数中,我将 ContextThemeWrapper 与我的工具栏主题一起使用:

class CustomToolBar : Toolbar {

    constructor(context: Context?) : super(ContextThemeWrapper(context, R.style.ToolBarTheme))

    constructor(context: Context?, attrs: AttributeSet?) : super(ContextThemeWrapper(context, R.style.ToolBarTheme), attrs) 

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(ContextThemeWrapper(context, R.style.ToolBarTheme), attrs, defStyleAttr)

}

推荐阅读