是否可以更改首选项标题内的图标颜色?

时间:2019-07-11 16:58:19

标签: java android

我已经在我的首选项头文件中添加了一些图标(作为SVG),并且我想使用Java更改它们的颜色(我的应用是可主题化的,我找不到其他方法可以根据主题)。

我已经尝试过以与按钮等类似的方式更改图标的颜色……我也无法使用“ app:tint”属性来更改颜色,并且也不会随主题更改不管我做什么。

这是首选项标头代码。我想更改“ ic_round_settings”的颜色。

<header
     android:fragment="com.appname.settings.fragment.GeneralSettingsFragment"
        android:icon="@drawable/ic_round_settings"
        android:title="@string/settings_general"
        android:summary="@string/settings_general_explain" />

2 个答案:

答案 0 :(得分:0)

要实现该行为,请像这样使用XML中的颜色引用

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
                android:id="@+id/btn_send"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?attr/colorAccent"
                android:tint="?attr/colorAccent"
                android:text="@string/chat_send_text"
                android:drawableTint="?attr/colorAccent"
                android:drawableRight="@drawable/ic_paper_plane"/>
</FrameLayout>

此外,在进行活动时,请确保您在使用setContentView(R.layout_your_layout_file)之前先设置主题**,否则在动态设置主题时必须调用recreate()

示例

override fun onCreate(savedInstanceState: Bundle?) {
    setTheme(whatever_theme_you_want_to_use)
    setContentView(R.layout.activity_cool)
    // Further view initialization
}

缺点是您必须在所有活动中明确setTheme,因为Android无法为开发人员提供更简便的方法来更改整个应用程序的主题。

答案 1 :(得分:0)

好的,我找到了一种方法。如果您将attr属性添加到首选项标题中,如下所示:

<header
        android:fragment="com.appname.settings.fragment.GeneralSettingsFragment"
        android:icon="?attr/ic_round_settings"
        android:title="@string/settings_general"
        android:summary="@string/settings_general_explain" />

并将该属性添加到values文件夹中的attr.xml文件:

<attr name="ic_round_settings" format="reference"/>

然后使用明暗版本的图标将其添加到styles.xml的主题类中,主题将更改:

<style name="Theme.BaseLightTheme" parent="Theme.AppCompat">
    <item name="ic_round_settings">@drawable/ic_round_settings_dark</item>
</style>
<style name="Theme.BaseDarkTheme" parent="Theme.AppCompat">
    <item name="ic_round_settings">@drawable/ic_round_settings_light</item>
</style>

在SVG图标文件中,将浅色SVG图标副本中的颜色从#000000更改为#ffffff:

<path
      android:fillColor="#000000"
      android:pathData=""/>

编辑:此功能在Android 4.4及更低版本上不起作用-图标完全不会显示

相关问题