使用带有Maps的SimpleAdapter和使用MatrixCursor的SimpleCursorAdapter填充ListView

时间:2014-04-16 18:25:16

标签: android android-listview simplecursoradapter simpleadapter matrixcursor

我的Android应用程序使用带有简单两行行的ListView。使用简单的静态数据填写列表。在这些情况下,我知道有两种不同的解决方案可以填写清单:

1)将SimpleAdapter与MapsList一起使用,将静态数据放入HashMaps。

2)将SimpleCursorAdapter与MatrixCursor一起使用,将静态数据作为行添加到MatrixCursor。

使用这两种方法有什么优点或缺点吗?例如,它们中的任何一个都会有性能损失吗?一种或另一种方法是否更受普遍青睐,如果是,为什么?

示例

应用程序的主要活动是ListActivity。我在ListActivity的onCreate方法中填写了内置的ListView。

考虑我在数组中定义了一些静态数据:

private static String fruits[][] =
    {
        { "Apple", "red" },
        { "Banana", "yellow" },
        { "Coconut", "white" }
    };

使用方法1)SimpleAdapter with ArrayList of Maps

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create an ArrayList of Maps and populate with fruits
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); 

    for (int i=0; i<fruits.length; i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("Fruit", fruits[i][0]);
        map.put("Color", fruits[i][1]);
        list.add(map);
    }

    // Create a SimpleAdapter using the ArrayList of Maps,
    // which maps the entries Fruit and Color to the Views text1 and text2
    String entries[] = { "Fruit", "Color" };
    int views[] = { android.R.id.text1, android.R.id.text2 };
    SimpleAdapter adapter = new SimpleAdapter(this,
            list, android.R.layout.two_line_list_item, entries, views);

    // Attach adapter to ListView
    setListAdapter(adapter);
}

使用方法2)使用MatrixCursor的SimpleCursorAdapter

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create a MatrixCursor and populate with fruits
    String columns[] = { "_id", "Fruit", "Color" };
    MatrixCursor cursor = new MatrixCursor(columns);

    for (int i=0; i<fruits.length; i++) {
        cursor.newRow()
            .add(i)
            .add(fruits[i][0])
            .add(fruits[i][1]);
    }

    // Create a SimpleCursorAdapter using the MatrixCursor,
    // which maps the entries Fruit and Color to the Views text1 and text2
    String entries[] = { "Fruit", "Color" };
    int views[] = { android.R.id.text1, android.R.id.text2 };
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            android.R.layout.two_line_list_item, cursor, entries, views, 0);

    // Attach adapter to ListView
    setListAdapter(adapter);
}

哪种方法更好?

0 个答案:

没有答案