如何使用XML或JSON数据填充ListView(在Android中)?

TIM*_*MEX 5 java xml android listview android-activity

我阅读了一个教程,它使用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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*rth 8

示例是使用a,CursorAdapter因为(如果我没记错的话)方法Cursor返回一个对象.我不知道是否有传递原始XML来创建列表的方法,但您可以使用名称/值对来使用SimplelistAdapter创建列表.NotesDbAdapterfetchAllNotesHashMap

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

// -- 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 );
Run Code Online (Sandbox Code Playgroud)