android - 自定义 attr 获取颜色返回无效值

标签 android android-custom-view

我有一个自定义 View ,我想在其中设置 TextView 的颜色。

我有

attrs.xml

<declare-styleable name="PropertyView">
    <attr name="propertyTitle" format="string" localization="suggested" />
    <attr name="showTitle" format="boolean" />
    <attr name="propertyTextColor" format="color" />
    <attr name="propertyTextSize" format="dimension" />
</declare-styleable>

我在布局文件中设置了

<com.something.views.PropertyView
    android:id="@+id/dwf_rAwayTeamTimePenaltyInput"
    style="@style/mw"
    propertyview:propertyTextSize="16sp"
    propertyview:propertyTitle="@string/AwayTeam"
    propertyview:showTitle="true"
    propertyview:propertyTextColor="@color/textLight" />

我在我的代码中设置了它

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PropertyView, 0, 0);

    showTitle = a.getBoolean(R.styleable.PropertyView_showTitle, false);
    String title = a.getString(R.styleable.PropertyView_propertyTitle);
    float textSize = a.getDimension(R.styleable.PropertyView_propertyTextSize, -1);
    int color = a.getColor(R.styleable.PropertyView_propertyTextColor, -1);
    textSize = textSize / getResources().getDisplayMetrics().scaledDensity;
    if(BuildConfig.DEBUG) Log.e(getClass().getName(), "Color set to: " + color);

    setShowTitle(showTitle);
    setTitle(title);
    if(textSize >= 0) mTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
    if(color != -1) mTitleTextView.setTextColor(color);

    a.recycle();

但是颜色一直返回-1。 我还尝试将颜色设置为 #000 当我这样做时,我得到的值为 -16777216

我也试过 a.getInteger 和 a.getInt

有人遇到过这个问题或建议吗?

解决方案,感谢 Alex Fu

getColor 无法处理引用

它现在正在使用

ColorStateList color = a.getColorStateList(R.styleable.PropertyView_propertyTextColor);
mTitleTextView.setTextColor(color);

最佳答案

您在示例中使用了对颜色的引用,但是根据您的 attrs.xml 文件,该属性必须是颜色类型,而不是引用。这可能是为什么当您使用十六进制颜色代码时它可以工作,但使用返回 -1 的引用。

如果您确实将格式更改为引用,您还应该将检索它的方法从 a.getColor() 更改为 a.getColorStateList()

关于android - 自定义 attr 获取颜色返回无效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17700862/

相关文章:

android - Android 中的自定义形状按钮

Android 绑定(bind)适配器不适用于 CustomView

android - 在应用 XML 属性之前恢复 View 状态

android - 无法用颜色填充多边形

java - 如何检查设备上是否存在应用程序?

android - 无法获取未知属性 'sonatypeRepo'

android - 在 Android 应用程序中存储 key 的最佳方式

android - polymer TogglePanel 在 iphone 上闪烁

java - 如何在 Android 中更改 Canvas 上颜料的颜色/厚度?

Android 海拔属性在模拟器的 ListView 中不起作用,但在 android studio 中显示正确的输出?