以编程方式设置Android LinearLayout背景

9
我有这样一个情况,需要在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

1
发布logcat日志对于找到应用崩溃的解决方案非常有帮助。 - Braj
下次请添加logcat。我认为你的minSdk不是11,而你正在运行这个程序在一个api<11的设备上,这将导致崩溃,因为activatedBackgroundIndicator是从api 11开始提供的。如果不是这种情况,请发布logcat以获取帮助。 - Sherif elKhatib
我知道activatedBackgroundIndicator在11之前的版本中不存在,我已经有了一个检查,这不是问题所在。 - Buffalo
侯赛因:那正是我的问题。 - Buffalo
不是的,它是在原装的LG Optimus One ROM上运行的。 - Buffalo
显示剩余3条评论
6个回答

14

我曾经遇到同样的问题,使用以下这段代码解决了它。

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更新时,我在自定义的列表适配器中使用了这个方法,效果很好。


1
谢谢解决方案!但是在JellyBean之前需要使用setBackgroundDrawable - Mikalai Daronin
这里有一个更简单的方法(https://dev59.com/ZFvUa4cB1Zd3GeqPyvme#14524876),*无需*硬编码... - user1521536

6

尝试这行代码

rootLayout.setBackgroundResource(d);

替代

rootLayout.setBackgroundDrawable(d);

5

试试这个

rootLayout.setBackgroundResource(R.drawable.image);

2
请尝试以下代码。
LinearLayout layout=(LinearLayout) findViewById(R.id.layoutImage);
layout.setBackgroundResource(R.drawable.bg);

2

按照已接受答案中的方式做是一个不好的想法。问题在于,您还需要调用列表的onItemCheckedStateChanged来更新所需的内容(例如操作栏标题)。

在这种情况下,当项目被选中时,您只需要简单地调用getListView().setItemChecked(position, true);,当它未被选中时则调用getListView().setItemChecked(position, false);


1
你可以使用类似下面这样的代码: TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.selectableItemBackgroun d, outValue, true); view.setBackgroundResource(outValue.resourceId); 它可以帮助你设置可选项背景。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接