我创建自己的样式属性,如下所示:
<attr name="color_foreground" format="color|reference" />
我在我的主题中给它一个价值,如下所示:
<item name="color_foreground">@color/blue</item>
如果我在我的布局中访问它(已设置为 contentView)
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="?color_foreground"
>
它就像一个魅力。但是如果我在膨胀的布局中做同样的事情,我会收到一个错误:
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.myInflatedLayout, null);
错误输出:
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f010005 a=-1}
06-27 20:33:37.340: E/AndroidRuntime(31616): at android.content.res.Resources.loadDrawable(Resources.java:1899)
06-27 20:33:37.340: E/AndroidRuntime(31616): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
06-27 20:33:37.340: E/AndroidRuntime(31616): at android.view.View.<init>(View.java:2810)
06-27 20:33:37.340: E/AndroidRuntime(31616): at android.widget.TextView.<init>(TextView.java:561)
06-27 20:33:37.340: E/AndroidRuntime(31616): at android.widget.TextView.<init>(TextView.java:554)
06-27 20:33:37.340: E/AndroidRuntime(31616): ... 48 more
二进制 XML 第 15 行实际上是我通过“?color_foreground”访问 attr 的行
如果我尝试获取这样的属性(在设置内容视图之后),几乎会发生同样的情况:
this.getResources().getColor(R.attr.color_foreground);
错误:
06-28 12:55:16.975: E/AndroidRuntime(7089): Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f010005
06-28 12:55:16.975: E/AndroidRuntime(7089): at android.content.res.Resources.getValue(Resources.java:1019)
06-28 12:55:16.975: E/AndroidRuntime(7089): at android.content.res.Resources.getColor(Resources.java:749)
06-28 12:55:16.975: E/AndroidRuntime(7089): at ***.MyActivity.onCreate(AppointmentListActivity.java:66)
06-28 12:55:16.975: E/AndroidRuntime(7089): at android.app.Activity.performCreate(Activity.java:4465)
06-28 12:55:16.975: E/AndroidRuntime(7089): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
06-28 12:55:16.975: E/AndroidRuntime(7089): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
06-28 12:55:16.975: E/AndroidRuntime(7089): ... 11 more