Android listview无法按预期工作

时间:2015-01-22 12:12:25

标签: android listview

我有这个代码最终会从数据库填充但是为了让它先工作我已经使用了下面的代码

  ListView mListView = (ListView) getActivity().findViewById(R.id.listView);

        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>( );
        HashMap<String, Object> listItem;
        listItem = new HashMap<String, Object>();
        for (int i = 0;i<=10;i++) {
            listItem.put("item", "orderTitles" + i);
            listItem.put("subitem", "orderDescriptions" + i);
            items.add(listItem);
        }
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.list_item_format, new String[]{"item", "subitem"}, new int[]{R.id.itemTitle, R.id.itemDescription});
        mListView.setAdapter(adapter);

问题是列表的输出只说OrderTitles10和OrderDescriptions10(列出10次),而不是递增计数。我做错了什么

3 个答案:

答案 0 :(得分:2)

将您的代码更改为:

 ListView mListView = (ListView) getActivity().findViewById(R.id.listView);

        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>( );
        HashMap<String, Object> listItem;

        for (int i = 0;i<=10;i++) {
            listItem = new HashMap<String, Object>();
            listItem.put("item", "orderTitles" + i);
            listItem.put("subitem", "orderDescriptions" + i);
            items.add(listItem);
        }
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.list_item_format, new String[]{"item", "subitem"}, new int[]{R.id.itemTitle, R.id.itemDescription});
        mListView.setAdapter(adapter);

答案 1 :(得分:2)

在for循环内初始化listItem以在HashMap中创建并添加两个值的新ArrayList

    for (int i = 0;i<=10;i++) {
        listItem = new HashMap<String, Object>();
        listItem.put("item", "orderTitles" + i);
        listItem.put("subitem", "orderDescriptions" + i);
        items.add(listItem);
    }

答案 2 :(得分:0)

  

在循环内初始化listitem并更改for循环条件,如下所示

 for (int i = 0;i<10;i++) {
    listItem = new HashMap<String, Object>();
    listItem.put("item", "orderTitles" + i);
    listItem.put("subitem", "orderDescriptions" + i);
    items.add(listItem);
}