动态使用HashMap填充listView中的列

时间:2017-09-21 21:09:36

标签: java android string listview

我正在使用HashMapTextView中的数据放入ListView内,但我无法动态填充列表,我只能将第一行作为输出。或者如何为哈希字符串执行每个操作。

代码 -

for (int i=0; i<result.length(); i++) {
    JSONObject notice = result.getJSONObject(0);
    id[i] = notice.getString(KEY_ID);
    name[i] = notice.getString(KEY_NAME);
    date_from[i] = notice.getString(KEY_DATE_FROM);
    date_to[i] = notice.getString(KEY_DATE_TO);

    ListView listView = (ListView) findViewById(R.id.listView1);

    list = new ArrayList<HashMap<String, String>>();

    HashMap<String, String> temp= new HashMap<String, String>();
    temp.put(FIRST_COLUMN, id[i]);
    temp.put(SECOND_COLUMN, name[i]);
    temp.put(THIRD_COLUMN, date_from[i]);
    temp.put(FOURTH_COLUMN, date_to[i]);
    list.add(temp);
    ListViewAdapters adapter = new ListViewAdapters(this, list);
    listView.setAdapter(adapter);
}

自定义ListViewAdapter -

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater=activity.getLayoutInflater();

    if(convertView == null){
        convertView=inflater.inflate(R.layout.colmn_row, null);

        txtFirst=(TextView) convertView.findViewById(R.id.name);
        txtSecond=(TextView) convertView.findViewById(R.id.gender);
        txtThird=(TextView) convertView.findViewById(R.id.age);
        txtFourth=(TextView) convertView.findViewById(R.id.status);

    }


    HashMap<String, String> map=list.get(position);
    txtFirst.setText(map.get(FIRST_COLUMN));
    txtSecond.setText(map.get(SECOND_COLUMN));
    txtThird.setText(map.get(THIRD_COLUMN));
    txtFourth.setText(map.get(FOURTH_COLUMN));

    return convertView;
}

1 个答案:

答案 0 :(得分:0)

从您共享的代码中,您将所有内容放在循环中,一次又一次地重新创建ArrayListListView。因此,您的列表和列表视图仅包含最后一项(一行)。这样做 -

ListView listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<HashMap<String, String>>();
for (int i=0; i<result.length(); i++) {
    JSONObject notice = result.getJSONObject(i);
    id[i] = notice.getString(KEY_ID);
    name[i] = notice.getString(KEY_NAME);
    date_from[i] = notice.getString(KEY_DATE_FROM);
    date_to[i] = notice.getString(KEY_DATE_TO);

    HashMap<String, String> temp= new HashMap<String, String>();
    temp.put(FIRST_COLUMN, id[i]);
    temp.put(SECOND_COLUMN, name[i]);
    temp.put(THIRD_COLUMN, date_from[i]);
    temp.put(FOURTH_COLUMN, date_to[i]);
    list.add(temp);
}
    ListViewAdapters adapter = new ListViewAdapters(this, list);
    listView.setAdapter(adapter);