【发布时间】:2012-06-21 06:04:52
【问题描述】:
我有一个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 的可绘制对象的黑色边框仍然可见,只有背景的白色部分被灰色替换。这是一个屏幕截图: p>
用drawable修复它
凭直觉,我用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 sn-p:
//If it's selected, highlight the background
if(position == mSelectedIndex)
convertView.setBackgroundResource(R.drawable.selectedmessage);
else
convertView.setBackgroundResource(0);
这样就达到了预期的效果,如下图:
问题:
为什么为我的ListView 元素指定一个矩形作为背景会覆盖整个视图,而指定颜色却可以让黑色边框显示出来?我很高兴它可以正常工作,但我想知道为什么 Android 会以这种方式呈现视图,以便了解更多关于 Android 如何呈现视图的信息。
其他说明:
- 我正在库存的 Android 3.2 模拟器中运行该项目,如果这样的话 区别。
- 一个线索可能是
light_gray颜色背景看起来比light_grayshape资源更暗。 -
我怀疑这有什么不同,但
light_gray是:<color name="light_gray">#FFCCCCCC</color>
【问题讨论】:
标签: android user-interface android-layout