我有一个自定义视图,我想设置一个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>
我将其设置在布局文件中。
<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);
a.getColor()
方法吗?你应该尝试使用a.getColorStateList()
代替。getColorStateList
可以理解实色和引用。 - Alex Fu