我有一种情况需要以编程方式在 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" >
我试过使用:
Drawable d = getActivity().getResources().getDrawable(android.R.attr.activatedBackgroundIndicator);
rootLayout.setBackgroundDrawable(d);
但是它崩溃了。有什么想法吗?
编辑:我也曾尝试使用:
rootLayout.setBackgroundResource(android.R.attr.activatedBackgroundIndicator);
10-08 15:23:19.018: E/AndroidRuntime(11133): android.content.res.Resources$NotFoundException: Resource ID #0x10102fd
最佳答案
我遇到了同样的问题,我使用这段代码修复了它。
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));
}
当检测到 SDK 上限并且工作正常时,我在我的自定义列表适配器中使用了它。
关于Android 以编程方式设置 LinearLayout 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781501/