首页 > 解决方案 > resolveAttribute 有时会返回 -1

问题描述

我正在尝试以编程方式获取主题特定值,如下所示:

MainActivity.getInstance()?.theme?.resolveAttribute(R.attr.settingsTint, value, true)
value.data // sometimes its -1

问题是有时返回的值是-1,而属性确实存在于 attr.xml 中,并且也在 style.xml 中使用。其他属性也确实返回其正确的资源 id 值。

任何人都知道有什么问题吗?

属性.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="Theme">
        .
        .
        .
        <attr name="settingsTint" format="color"/> 
        .
        .
        .
    </declare-styleable>

</resources>

样式.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
<!--    Theme.AppCompat.Light.NoActionBar-->
    <style name="AppTheme" parent="Theme.MaterialComponents">
        <item name="settingsTint">@color/settingsTint</item>

    </style>

    <style name="AppTheme.Dark" parent="AppTheme">
        <item name="settingsTint">@color/settingsTint_dark</item>
    </style>

</resources>

显现:

<application
        android:theme="@style/AppTheme"
<activity
            android:theme="@style/AppTheme">

甚至在我更改主题之前的某个时候,我检查了MainActivity.getInstance()?.theme?.resolveAttribute(R.attr.settingsTint, value, true) 我之前所说的值,我看到 -1

谢谢!

标签: androidandroid-attributes

解决方案


也许你可以TypedValue.type在使用它之前检查一下。

if (tv.type == TypedValue.TYPE_STRING){
    ...
}else if(tv.type == TypedValue.NULL){
    ...
}

推荐阅读