它必须是网格视图吗?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>
请注意,我使用“left”和“right” android: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 );
} // end of initListView()
MatrixCursor 构造函数的参数是一个字符串数组,用于定义光标中列的顺序和名称。重要提示:确保添加一个“_id”列,没有它,MatrixColumn 将抛出异常并且无法工作!
三个变量 mAuthor、mCopyright 和 mPrice 是我的 ListAdaptor 类中的三个数据成员,它们在别处初始化。在我的实际代码中,mAuthor 实际上是根据作者姓名列表在此方法中构建的。作者姓名使用“\n”作为姓名之间的分隔符连接成一个字符串。这会导致多个作者姓名出现在同一 TextView 的不同行上。
SimpleCursorAdapter ctor 参数是用于每个 List 行的 View 的 ID、包含数据的游标、字符串数组,其中每个元素是游标中列的名称(按获取它们的顺序)和对应的用于列表行中每个项目的视图的视图 ID 数组。