为什么为ListView元素的背景指定颜色不会覆盖整个ListView背景,同时分配一个drawable呢?

时间:2012-06-21 06:04:52

标签: android user-interface android-layout

我有ListView位于平板电脑尺寸屏幕的左侧。我的目标是给它一个带有右边框的坚实背景,然后在列表元素上应用重叠背景来打破该边框,使其看起来是右边视图的一部分。


ListView背景

我使用<layer-list> drawable as suggested by Emile in another question获得了正确的边框:

rightborder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/black" />
        </shape>
    </item>
    <item android:right="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>

</layer-list>

...这里是ListView定义的好措施:

<ListView
    android:id="@+id/msglist"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:divider="@color/black"
    android:dividerHeight="1dp"
    android:background="@drawable/rightborder"
    android:paddingRight="0dip">
</ListView>
<!-- I added the android:paddingRight after reading something 
about shape drawables and padding, don't think it actually
did anything. -->

尝试用颜色覆盖

为了达到预期的效果,我将以下内容放在我的适配器的getView函数中:

//If it's selected, highlight the background
if(position == mSelectedIndex)
    convertView.setBackgroundColor(R.color.light_gray);

else
    convertView.setBackgroundResource(0);

然而,使用此方法, ListView的drawable的黑色边框仍然可见,并且只有背景的白色部分被灰色替换。这是一个截屏:

Border showing through color background


用可绘制的

修复它

在预感中,我用shape drawable替换了我分配的颜色:

selectedmessage.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/light_gray" />
</shape>

getView代码段:

//If it's selected, highlight the background
if(position == mSelectedIndex)
    convertView.setBackgroundResource(R.drawable.selectedmessage);

else
    convertView.setBackgroundResource(0);

这可以达到预期的效果,如下所示:

Border no longer showing


问题:

为什么指定一个矩形作为我ListView元素的背景覆盖整个视图,而指定颜色则允许显示黑色边框?我很高兴它的工作正常,但我想知道为什么Android会以这种方式呈现视图,这样我就可以了解更多有关Android渲染视图的信息。

其他说明:

  • 我在Android 3.2模拟器中运行该项目,如果这样做的话 差。
  • 一条线索可能是light_gray颜色背景似乎比light_gray shape资源更暗。
  • 我怀疑它有所不同,但light_gray是:

    <color name="light_gray">#FFCCCCCC</color>

1 个答案:

答案 0 :(得分:1)

你不能这样做:

 convertView.setBackgroundColor(R.color.light_gray);

setBackgroundColor不接受资源ID:http://developer.android.com/reference/android/view/View.html#setBackgroundColor(int)

所以你得到了一些不符合你期望的偶然行为。

你必须这样做:

 convertView.setBackgroundColor(getResources().getColor(R.color.light_gray);

http://developer.android.com/reference/android/content/res/Resources.html#getColor(int)