在使用 ListViews 时,我遇到了一个有趣的问题。所以我的目标是为自定义 ListView 项设计编写一个 xml 布局。
首先,这里是有问题的xml布局(下面描述的问题):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="?android:attr/activatedBackgroundIndicator" >
<TextView
android:id="@+id/notebook_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceLarge"
android:layout_toRightOf="@+id/notebook_color_tag"
/>
<View
android:id="@+id/notebook_color_tag"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
/>
</RelativeLayout>
布局相当基本,只有一个View
,用于显示颜色,和一个TextView
。
我有一个 ListFragment
的子类,它在其 setListAdapter()
方法中使用了 CursorAdapter
的一个子类实例。在自定义 CursorAdpater
的 bindView()
中,我设置了 View
的颜色和 TextView
的文本(那段代码不是问题,可以忽略,仅供引用):
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView notebookName = (TextView) view.findViewById(R.id.notebook_title);
View colorTag = view.findViewById(R.id.notebook_color_tag);
String name = cursor.getString(NOTEBOOK_NAME_POS);
int color = cursor.getInt(NOTEBOOK_COLOR_POS);
notebookName.setText(name);
colorTag.setBackgroundColor(color);
}
现在,问题是如果 View
的 android:layout_height
设置为 match_parent
或 wrap_content
,View
根本不会出现在 ListView
的项目中。它似乎在顶部有一些余量。如果指定了具体的宽度值,例如:android:layout_height="40dp"
,一切正常。
这是伪造布局的样子:
它应该是这样的:
如上所述,蓝色矩形似乎根本不在 ListView
的项目容器内(但元素在那里,可以通过 findViewById()
访问) > 并且它的颜色确实通过 setBackgroundColor()
调用改变了,View
似乎根本没有显示)。
布局的以下更改解决了问题:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal"
android:background="?android:attr/activatedBackgroundIndicator" >
<View
android:id="@+id/notebook_color_tag"
android:layout_marginTop="0dp"
android:layout_width="20dp"
android:layout_height="match_parent"
/>
<TextView
android:id="@+id/notebook_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceLarge"
/>
</LinearLayout>
我知道 LinearLayout
在这里比 RelativeLayout
更有意义,但我很好奇 RelativeLayout
的情况出了什么问题.
最佳答案
您有重复的“notebook_color_tag”ID。您在第一个布局 XML 中添加了两次(作为 TextView
中的参数,也作为布局的子项)。
另外,我会颠倒顺序,像这样:
<View
android:id="@+id/notebook_color_tag"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="@+id/notebook_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceLarge"
android:layout_toRightOf="@id/notebook_color_tag"
/>
由于 RelativeLayout
将按 XML 的顺序创建和放置,因此效率更高(它不必重新测量以正确放置 View 。
关于android - 在 ListView 中使用 RelativeLayout 时 View 的背景颜色被移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32321949/