Android以编程方式设置LinearLayout背景



我有需要以编程方式在LinearLayout上设置背景的情况。

在我的布局中,我使用"android:background="?android:attr/activated BackgroundIndicator"设置我的背景,但我想以编程方式设置:

<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

我遇到了同样的问题,我用这段代码修复了它。

机器人。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 上部并且工作正常时,我在自定义列表适配器中使用它。

试试这一行

rootLayout.setBackgroundResource(d);

而不是

rootLayout.setBackgroundDrawable(d);

试试这个

rootLayout.setBackgroundResource(R.drawable.image);

按照接受的答案告诉你的方式去做是个坏主意。问题是您还需要调用列表的onItemCheckedStateChanged来更新所需的内容(例如操作栏标题)。

在这种情况下,您需要做的就是在选中项目时调用getListView().setItemChecked(position, true);,在未选中项目时调用getListView().setItemChecked(position, false);

请尝试以下代码。

LinearLayout layout=(LinearLayout) findViewById(R.id.layoutImage);
layout.setBackgroundResource(R.drawable.bg);

你可以使用这样的东西

TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.selectableItemBackgroun d, outValue, true); view.setBackgroundResource(outValue.resourceId);

最新更新