gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:26:19 28 4
gpt4 key购买 nike

我有一个自定义 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com