Android 以编程方式设置 LinearLayout 背景

标签 android layout

我有一种情况需要以编程方式在 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/

相关文章:

Android 应用程序无法连接到 Rocket Chat 服务器

android - 错误 : jest-haste-map: Haste module naming collision:

css - 为什么 div 之间存在虚假的过度分隔?

ios - 如何在 iOS 中创建类似于 yelp 的复杂 ScrollView ?

android - key 错误 : 'ANDROID_APP_PATH'

android - 仅在网络中关闭套接字 v4.0 ksoap2

css - DIV 不会一直延伸到页面底部吗?

html - div 保持在顶部,但应随网站移动

android - 操作栏 Sherlock + ListFragments + Fragments

android - CustomListView后台问题