我有一种情况需要以编程方式在LinearLayout上设置背景.
在我的布局中,我使用`android:background ="?android:attr/activatedBackgroundIndicator"设置我的背景,但我想以编程方式设置它:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayoutId"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="left|center"
android:paddingBottom="5dip"
android:paddingLeft="5dip"
android:background="?android:attr/activatedBackgroundIndicator"
android:paddingTop="5dip" >
Run Code Online (Sandbox Code Playgroud)
我尝试过使用:
Drawable d = getActivity().getResources().getDrawable(android.R.attr.activatedBackgroundIndicator);
rootLayout.setBackgroundDrawable(d);
Run Code Online (Sandbox Code Playgroud)
但它崩溃了.有任何想法吗?
编辑:我也尝试过使用:
rootLayout.setBackgroundResource(android.R.attr.activatedBackgroundIndicator);
10-08 15:23:19.018: E/AndroidRuntime(11133): android.content.res.Resources$NotFoundException: Resource ID #0x10102fd
Run Code Online (Sandbox Code Playgroud)
mla*_*aca 13
我有同样的问题,我使用这段代码修复它.
android.R.attr.*是指向主题的指针,而不是指定的实际可绘制资源.您必须使用TypedArray来访问ID.
theView = this.inflater.inflate(R.layout.list_row_job_favorited, null);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
TypedArray a = mContext.obtainStyledAttributes(new int[] { android.R.attr.activatedBackgroundIndicator });
int resource = a.getResourceId(0, 0);
//first 0 is the index in the array, second is the default value
a.recycle();
theView.setBackground(mContext.getResources().getDrawable(resource));
}
Run Code Online (Sandbox Code Playgroud)
我在自定义列表适配器中使用它时检测到SDK上层并且工作正常.
试试这一行
rootLayout.setBackgroundResource(d);
Run Code Online (Sandbox Code Playgroud)
代替
rootLayout.setBackgroundDrawable(d);
Run Code Online (Sandbox Code Playgroud)