java - TypedArray getColor 总是返回 defValue

标签 java android xml android-layout

在我的 XML 元素中,我尝试传递来自 colors.xml 资源文件的颜色。 getColor 函数总是返回 defValue,即使它应该返回 colors.xml 中给定的颜色。

代码

TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
final int col_pressed = a.getColor(R.styleable.accordion_buttonColorPressed, Color.BLACK);
final int col_unpressed = a.getColor(R.styleable.accordion_buttonColorPressed, Color.YELLOW);
btn.setBackgroundColor(col_unpressed);

主要 XML

<mika.actual.AccordionWidget
    xmlns:accordion="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    accordion:text_color="@color/text_color"
    accordion:buttonColorPressed="@color/button_pressed"
    accordion:buttonColorUnpressed="@color/button_not_pressed"
    android:background="#FFFFFFFF"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"> ... </mika.actual.AccordionWidget>

颜色.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="text_color">#FFFFFF</color>
    <color name="button_pressed">#666666</color>
    <color name="button_not_pressed">#BBBBBB</color>
</resources>

属性.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="accordion">
        <attr name="text_color" format="color"/>
        <attr name="buttonColorPressed" format="color"/>
        <attr name="buttonColorUnpressed" format="color"/>
    </declare-styleable>
</resources>

最佳答案

这是一个旧线程,但没有人响应。我会的,这样观众就有答案了 我认为你只需要像这样将所有 accordion: 更改为 app:

app:text_color="@color/text_color"
app:buttonColorPressed="@color/button_pressed"
app:buttonColorUnpressed="@color/button_not_pressed"

关于java - TypedArray getColor 总是返回 defValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36202571/

相关文章:

java - 不循环并显示错误消息

java - Java Servlet中Json字符串解析并插入数据库

xml - 如何将多个 XML 中的值提取到 Excel 中?

java - 如何定义具有自引用类型返回值的方法

java - 启动在 RAM 内存中创建的文件

Android ViewPager 在 Galaxy Tab 2 上的性能

android - 如何使用导航 Controller 组件设置不同的工具栏?

android - Toast消息长度

c# - 将xml数据显示成html

java - 如何在values-v21中使用语言更改strings.xml?