自定义属性获取颜色返回无效值

自定义属性获取颜色返回无效值

本文介绍了自定义属性获取颜色返回无效值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图,我想在其中设置文本视图的颜色.

I have a custom view in which i want to set the color of a textview.

我有

attrs.xml

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>

我将其设置在布局文件中

I set it in the layout file

<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" />

然后在我的代码中进行设置

And in my code I set it

    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

But color keeps returning -1.I also tried to set color to #000When i do that i get a value of -16777216

我也尝试了a.getInteger和a.getInt

I also tried a.getInteger and a.getInt

任何人对此问题或建议有经验吗?

Anyone experience with this problem or suggestions?

解决方案,感谢Alex Fu

getColor无法处理引用

getColor cannot handle references

现在可以使用

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

推荐答案

您在示例中使用了对颜色的引用,但是根据attrs.xml文件,该属性必须为颜色类型,不是参考.这可能是为什么您使用十六进制颜色代码有效但使用引用返回-1的原因.

You are using a reference to a color in your example, however according to your attrs.xml file, that property must be of a color type, not a reference. This is probably the reason why when you used a hex color code it worked, but using a reference returned -1.

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

If you do change the format to a reference, you should also change the method to retrieve it from a.getColor() to a.getColorStateList().

这篇关于自定义属性获取颜色返回无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:36