如何以编程方式获取颜色属性的值

Ωme*_*ega 4 java android android-layout android-theme android-resources

当我resolveAttribute()用来找出颜色值时?attr/colorControlNormal,我得到了236:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
// 236 
Run Code Online (Sandbox Code Playgroud)

但是当我使用带有以下TextView元素的XML布局时:

<TextView
  android:id="@+id/textView"
  style="?android:attr/textAppearance"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textColor="?attr/colorControlNormal"
  android:text="@null" />
Run Code Online (Sandbox Code Playgroud)

...以及以下Java代码:

View textView = findViewById(R.id.textView);
int color = ((TextView) textView).getCurrentTextColor();
// -1979711488
Run Code Online (Sandbox Code Playgroud)

我的颜色值是 -1979711488


为何结果有所不同?我希望得到相同的颜色值,但它们不是.

第二种方法(我相信)返回正确的颜色值.为什么我的第一种方法错了?

我宁愿获得颜色值?attr/colorControlNormal而不需要使用实际元素.我怎样才能做到这一点?

azi*_*ian 9

我相信而不是这个:


    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
    int color = typedValue.data;

你应该做这个:


    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
    int color = ContextCompat.getColor(this, typedValue.resourceId)