【问题标题】:How do I fill a ListView (in Android) with XML or JSON data?如何用 XML 或 JSON 数据填充 ListView(在 Android 中)?
【发布时间】:2010-02-09 06:14:14
【问题描述】:

我阅读了一个教程,它使用 SQLlite 和“SimpleCursorAdapter”来用项目填充列表。 这是教程教给我的代码。

private void fillData() {
        // Get all of the notes from the database and create the item list
        Cursor c = mDbHelper.fetchAllNotes();
        startManagingCursor(c);

        String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
        int[] to = new int[] { R.id.text1 };

        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
        setListAdapter(notes);
    }

但是...如果我想用 XML 数据填充它怎么办?是一样的方法吗?有人可以给我一个例子(在代码中)吗?谢谢。

【问题讨论】:

    标签: java xml android listview android-activity


    【解决方案1】:

    该示例使用CursorAdapter,因为NotesDbAdapter(如果我没记错的话)fetchAllNotes 方法返回了Cursor 对象。我不知道是否有办法传入原始 XML 来创建列表,但您可以使用 HashMap 中的名称/值对来使用 SimplelistAdapter 创建列表。

    您可以解析您的 xml 和/或 json 并使用它构建一个哈希表并使用它来填充列表。下面的示例没有使用 xml,实际上它根本不是动态的,但它确实演示了如何在运行时组装列表。它取自扩展ListActivity 的活动的onCreate 方法。所有大写的值都是定义在类顶部的静态常量字符串,用作键。

    // -- container for all of our list items
    List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
    
    // -- list item hash re-used
    Map<String, String> group;
    
    // -- create record
    group = new HashMap<String, String>();
    
    group.put( KEY_LABEL, getString( R.string.option_create ) );
    group.put( KEY_HELP,  getString( R.string.option_create_help ) );
    group.put( KEY_ACTION, ACTION_CREATE_RECORD );
    
    groupData.add(group);
    
    // -- geo locate
    group = new HashMap<String, String>();
    
    group.put( KEY_LABEL, getString(R.string.option_geo_locate ) );
    group.put( KEY_HELP, getString(R.string.option_geo_locate_help ) )
    group.put( KEY_ACTION, ACTION_GEO_LOCATE );
    
    groupData.add( group );
    
    // -- take photo
    group = new HashMap<String, String>();
    
    group.put( KEY_LABEL, getString( R.string.option_take_photo ) );
    group.put( KEY_HELP, getString(R.string.option_take_photo_help ) );
    group.put( KEY_ACTION, ACTION_TAKE_PHOTO );
    
    groupData.add( group );
    
    // -- create an adapter, takes care of binding hash objects in our list to actual row views
    SimpleAdapter adapter = new SimpleAdapter( this, groupData, android.R.layout.simple_list_item_2, 
                                                       new String[] { KEY_LABEL, KEY_HELP },
                                                       new int[]{ android.R.id.text1, android.R.id.text2 } );
    setListAdapter( adapter );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2012-09-16
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多