0

我正在为Android开发一个应用程序

我有不同的类别:

String[] cat = { "Category",  "Books", "Clothing", "Shoes", "Hobbies", 
                 "General", "Electronics", "Transportation", "Medicine",
                 "Sports", "Education", "Outdoor"};

UI 要求用户选择一个类别、名称和一些描述,然后将其写入数据库。当用户按下 List 按钮时,将显示每个已填充的类别,并且该类别下的项目也使用ExpandableListActivity显示。

List<List<String>> children = new ArrayList<List<String>>();

/**********************
  I have a list for each category!!! But I don't like this solution. :(
**********************/
List<String> books = new ArrayList<String>();
List<String> clothing = new ArrayList<String>();
    ...
    ...

public void fillData() {

// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllItems();

startManagingCursor(c);

// for all rows
for(int i=0; i<c.getCount(); i++)
{
    // next row
    c.moveToNext();

    // pick a category
    String t = c.getString(c.getColumnIndex("category"));

    switch (getCat(t))
    {
    case Books:
        books.add(c.getString(c.getColumnIndex("name")));
        break;
    case Clothing:
            // do stuff for Clothing
        break;

     /**
       And there are other cases for the rest of the categories but i am not listing
       them here, since it is the same process
     */
        default:
        break;
    }   // end switch
} // end for loop

    //for each category that has been filled up
    children.add(category);
} // end function

我的问题:

是否可以不必为每个类别创建一个列表?我尝试了一个列表,但结果看起来不太好。所有类别都显示相同的项目,而不是单个项目,这是有道理的。

4

2 回答 2

0

您不需要自己创建列表。

您可能需要 2 个表 - 一个列出类别名称及其 id(这将是主表键),另一个列出每行具有项目的类别 id、项目名称以及单个项目的任何其他内容的东西。

然后你可以有SimpleCursorTreeAdapter这样的:

SimpleCursorTreeAdapter (Context context, Cursor cursor, int groupLayout, String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom, int[] childTo).

因为groupLayout你会有android.R.layout.simple_expandable_list_item_1. 因为childLayout你会有android.R.layout.simple_list_item_1

因为groupFrom你会有

字符串[] groupFrom = { FLD_CATEGORY_NAME }; int[] groupTo = { android.R.id.text1 };

对于 childFrom 你将拥有

String[] childFrom = { FLD_ITEM_NAME };
int[] childTo = { android.R.id.text1 };

如果您想显示超过 1 或 2 个元素,或者更确切地说是您自己的布局

你会有

protected Cursor getChildrenCursor(Cursor groupCursor) {
      int categoryId = groupCursor.getColumnIndex(FLD_CATEGORY_ID);
      // and here you a Cursor from your items table WHERE CTAEGORY_ID == categoryId
}
于 2012-07-27T19:06:58.140 回答
0

我刚刚创建了一个列表列表,并且工作了:)

于 2012-07-31T17:31:57.690 回答