我的应用程序中有一个对话框片段,其中列出了一些值,例如:数据库表中的:dresses.我想以“将值分组”的方式显示列表.即,该列表应在每个标题下方显示男人,女人,孩子和他们的衣服的标题.
同样在数据库中,有一列包含这些男人,女人,孩子的值.因此,引用该列应对列表进行排序.
解决方法:
正如其他人所说,您需要使用ExpandableListView为游标提供适当的数据.您没有提到数据库架构,因此我假设您只有一个带衣服的表,并且该表还具有(除了衣服名称和其他数据之外)用于放置男人,女人,孩子等的type列.
您可以通过首先查询数据库以检索3种衣服的类型,然后在适配器中返回包含该特定类型衣服的游标,来执行所需的操作.以下是有关如何执行此操作的示例:
// I'm assumming that your database table is called "clothes" and the
// column holding the type is called "type"
sqliteDatabase db= /*get the database*/;
// this query will return a cursor containing 3 rows(for man, woman, child)
Cursor typesCursor = db.rawQuery("SELECT * FROM clothes GROUP BY type", null);
expandableListViewWidget.setAdapter(new CustomAdapter(typesCursor, this, db));
以下是用于处理每种衣服类型的子数据的自定义适配器:
public static class CustomAdapter extends CursorTreeAdapter {
private sqliteDatabase mDb;
private LayoutInflater mInflater;
public CustomAdapter(Cursor cursor, Context context, sqliteDatabase db) {
super(cursor, context);
mDb = db;
mInflater = LayoutInflater.from(context);
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
// find which type of clothes you're dealing with and return the data only for that type
final String type = groupCursor.getString(groupCursor.getColumnIndex("type"));
return mDb.rawQuery("SELECT * FROM clothes WHERE type=?", new String[]{type});
}
@Override
protected View newGroupView(Context context, Cursor cursor, boolean isExpanded, ViewGroup parent) {
// here you'll return the view for the group rows
View v = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
return v;
}
@Override
protected void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded) {
// here you'll bind the type of clothes to the group view
String type = cursor.getString(cursor.getColumnIndex("type"));
// bind the data to the views
}
@Override
protected View newChildView(Context context, Cursor cursor, boolean isLastChild, ViewGroup parent) {
// here you'll return the view for the child rows
View v = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
return v;
}
@Override
protected void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) {
String clothes = cursor.getString(cursor.getColumnIndex("clothes_name")); // assmuning that you keep the clothes name in this column
// bind the data to the views
}
}