如何填写(在Android设备)一个ListView与XML或JSON数据?
-
19-09-2019 - |
题
我读的教程,它使用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数据来填补呢?难道同样的方法?有人可以给我一个例子(代码)?感谢。
解决方案
在的例子是使用CursorAdapter
因为Cursor
目的通过返回NotesDbAdapter
(如果没有记错)fetchAllNotes
方法。我不知道是否有一种方法在原始XML通过创建一个列表,但你可以使用名称/值对在HashMap
使用SimplelistAdapter创建列表。
您可以分析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 );
不隶属于 StackOverflow