Android 小部件:带有 TextView 的 RemoteViews android.content.res.Resources$NotFoundException

Android Widget: RemoteViews with TextView android.content.res.Resources$NotFoundException

最近我们将应用程序中的 targetSDK 从 21 更新到 23。

android {
  compileSdkVersion 23
  buildToolsVersion '23.0.1'
  ...

defaultConfig {
  applicationId 'com.myapp'
  minSdkVersion 15
  targetSdkVersion 23
  versionCode System.getenv("LAST_BUILD_NUMBER") as Integer ?: 1514261001
  versionName '2.6.1' + (System.getenv("APP_VERSION_SUFFIX") ?: '')
  testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
  multiDexEnabled true
}

我们的应用程序还有一些小部件,其中包含一些像这样的 TextView:

        <TextView
           android:id="@+id/txt_sunrise"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:drawableLeft="@drawable/ic_classic_weather_sunrise"
           android:drawablePadding="6dp"
           android:text="-"
           android:textColor="@android:color/white"
           android:textSize="@dimen/largeTextSizeAstro" />

小部件是这样构建的:

RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_large);
rv.setTextViewText(R.id.txt_sunrise, sunrise);
// some more code
appWidgetManager.updateAppWidget(appWidgetId, rv);

在 Android 5.0 上一切正常,但在某些 Android 4.x 设备上(我可以在某些三星设备以及 Genymotion 模拟器上重现它),我得到了一个例外,应该构建小部件的时间:

caused by: android.content.res.Resources$NotFoundException: Resource is not a ColorStateList (color or path): TypedValue{t=0x2/d=0x7f01018e a=2}
at android.content.res.Resources.loadColorStateList(Resources.java:2074)
at android.content.res.TypedArray.getColorStateList(TypedArray.java:342)
at android.widget.TextView.<init>(TextView.java:912)
at android.widget.TextView.<init>(TextView.java:578)

查看给定的resource-Id 0x7f01018e,发现这是应用主题中定义的colorAccent,当然不是颜色状态列表

<style name="AppTheme" parent="Theme.AppCompat">
  <item name="colorPrimary">@color/grey_darker</item>
  <item name="colorPrimaryDark">#111111</item>
  <item name="colorAccent">@color/orange</item>

知道为什么我会收到这个错误吗?

我在特定平台和给定的行号上深入研究了 android Textview 的源代码,我在构造函数方法中找到了这个片段:

case com.android.internal.R.styleable.TextView_textColorLink:
     textColorLink = a.getColorStateList(attr);
     break;

我的解决方案现在是将以下行添加到我的主题中,然后小部件再次运行:

<item name="android:textColorLink">@color/selector_classic_link</item>

注意:selector_classic_link 是在 xml 中定义的 ColorStateList。