它一定要是网格视图吗?ListView可行吗?
我编写了一个ListView和ListActivity,每行显示两个项。我从SDK提供的simple_list_item_2.xml布局开始,该布局每行列出两个项目,但将其放置在彼此上方(两行),第二行使用较小的字体。我想要的是两个项目在同一行上,一个在左侧,一个在右侧。
首先,我将simple_list_item_2.xml复制到我的项目的res/layout目录下,并用新名称更改属性android:mode ="twoLine"为"oneLine",同时仍将视图元素名称保留为"TwoLineListItem"。然后,我替换了两个内部元素,使其符合我的要求。
在初始化列表的代码中,我创建了一个MatrixCursor并填充了所需的数据。为支持两个项目,MatrixCursor中的每行需要三个列,其中一个是主键“_id”,另外两个列是我想要显示的项目。然后,我能够使用SimpleCursorAdapter来填充和控制ListView。
我的布局XML文件:
<?xml version="1.0" encoding="utf-8"?>
<TwoLineListItem
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="2dip"
android:paddingBottom="2dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:mode="oneLine"
>
<TextView
android:id="@android:id/text1"
android:gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
android:id="@android:id/text2"
android:gravity="right"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:layout_marginRight="6dip"
android:layout_toRightOf="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/MainFontColor"
/>
</TwoLineListItem>
请注意,我使用了“左”和“右”android:gravity值,以使左侧项目左对齐,右侧项目右对齐。您需要不同的gravity值来适应您的布局,还需要控制左侧项目的大小属性,这是我不需要的。
在我的ListActivity类中初始化ListView的方法:
private void initListView()
{
final String AuthorName = "Author: ";
final String CopyrightName = "CopyRight: ";
final String PriceName = "Price: ";
final String[] matrix = { "_id", "name", "value" };
final String[] columns = { "name", "value" };
final int[] layouts = { android.R.id.text1, android.R.id.text2 };
MatrixCursor cursor = new MatrixCursor(matrix);
DecimalFormat formatter = new DecimalFormat("##,##0.00");
cursor.addRow(new Object[] { key++, AuthorName, mAuthor });
cursor.addRow(new Object[] { key++, CopyrightName, mCopyright });
cursor.addRow(new Object[] { key++, PriceName,
"$" + formatter.format(mPrice) });
SimpleCursorAdapter data =
new SimpleCursorAdapter(this,
R.layout.viewlist_two_items,
cursor,
columns,
layouts);
setListAdapter( data );
}
MatrixCursor构造函数的参数是一个字符串数组,用于定义游标中列的顺序和名称。重要提示:确保添加一个"_id"列,否则MatrixColumn将抛出异常并无法工作!
三个变量mAuthor、mCopyright和mPrice是我ListAdaptor类中的三个数据成员,并在其他地方初始化。在我的实际代码中,mAuthor实际上是从作者名称列表中使用"\n"作为分隔符组合成单个字符串的方法构建的。这会导致多个作者名称在同一个TextView中显示在不同的行上。
SimpleCursorAdapter构造函数的参数是用于每个列表行使用的视图的ID、包含数据的游标、一个字符串数组,其中每个元素都是来自游标的列名(按照获取它们的顺序),以及对应的View IDs数组,用于在每个列表行中使用的View。