我的应用程序中有一个对话框 fragment ,其中列出了一些值,例如:数据库表中的连衣裙。我想以“值已分组”的方式显示列表。也就是说,列表中应显示标题为“男士”、“女士”、“ child ”以及每个标题下方的礼服。 另外 在数据库中有一列包含这些men,women,kids 值。因此,引用该列应该对列表进行排序。
最佳答案
正如其他人所说,您需要使用 ExpandableListView
为游标提供适当的数据。你没有提到你的数据库模式,所以我假设你只有一张衣服表,而且这张表还有(除了衣服名称和其他数据)你放男人、女人、 child 等的类型列。
您可以通过首先查询数据库来检索 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
}
}
关于android - 从数据库中获取数据时如何对列表中的行进行分组并给出标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25763934/