【问题标题】:setBackgroundColor(drawable) != android:background=(drawable)?setBackgroundColor(drawable) != android:background=(drawable)?
【发布时间】:2011-01-17 23:10:11
【问题描述】:

我有一个自定义可绘制资源来在 ListView 中显示我的项目,实际上是两个,因为我希望我的结果具有交替的背景颜色,但两者都通过更改颜色来响应点击。问题是即使通过布局 XML 将这些可绘制对象中的一个分配给我的 LinearLayout 容器,它也可以正常工作,但通过 Java 代码却不能。确切地说,这是可行的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/result_white"
android:id="@+id/result"
>

但是这个(在我扩展 ArrayAdapter 的 ResultAdapter 中)没有:

LinearLayout result = (LinearLayout) v.findViewById(R.id.result);
result.setBackgroundColor(R.drawable.result_white);

我的最终目标当然是为结果交替使用“result_white”和“result_ltgray”可绘制对象,因此第一个 XML 解决方案并不能真正满足我的需求。请问我在 Java 代码中遗漏了什么?

【问题讨论】:

    标签: android listview drawable listactivity


    【解决方案1】:

    好吧,假设你只使用一种颜色的背景,你应该改用Colors,因为drawables可以是形状、渐变等等。现在,要实际使用颜色,您的代码将如下所示:

    result.setBackgroundColor(mContext.getResources.getColor(R.color.result_white));
    

    其中 mContext 是上下文,并且您的 res/values/colors.xml 文件中有一个颜色(例如 0xFFFFFFFF)。

    还可以查看Color State Lists 以了解在按下/选择/等时更改颜色

    【讨论】:

      【解决方案2】:

      感谢你们的帮助,但我需要做的是:

      result.setBackgroundResource(R.drawable.result_white);
      

      这样我可以轻松地将其实现到我的 ResultAdapter 中,以交替结果以响应随着背景变化的点击:

      LinearLayout result = (LinearLayout) v.findViewById(R.id.result);
      
              if (position % 2 == 0)
                  result.setBackgroundResource(R.drawable.result_white);
              else
                  result.setBackgroundResource(R.drawable.result_ltgray);
      

      【讨论】:

        【解决方案3】:

        确保您为 R 导入了正确的参考(android.R 用于 android drawables,your_app_path.R 用于您自己的)。

        【讨论】:

          猜你喜欢
          • 2011-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多