Android如何将一个HashMap<String, List<String>>中的value值赋值给Item有两行字的Listview
时间: 2024-05-10 18:15:33 浏览: 147
可以使用自定义的Adapter来实现这个功能。下面是一个简单的示例代码:
首先,定义一个自定义的Adapter类,继承BaseAdapter:
```
public class MyAdapter extends BaseAdapter {
private HashMap<String, List<String>> mData;
public MyAdapter(HashMap<String, List<String>> data) {
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.keySet().toArray()[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.textView = convertView.findViewById(R.id.item_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String key = (String) getItem(position);
List<String> values = mData.get(key);
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append(value).append(" ");
}
holder.textView.setText(sb.toString());
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
```
然后,在布局文件中定义一个ListView,以及一个Item布局,例如:
```
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"/>
</LinearLayout>
```
最后,在Activity中使用Adapter来设置ListView的数据源,例如:
```
HashMap<String, List<String>> data = new HashMap<>();
data.put("Item1", Arrays.asList("Value1", "Value2"));
data.put("Item2", Arrays.asList("Value3", "Value4"));
data.put("Item3", Arrays.asList("Value5", "Value6"));
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(new MyAdapter(data));
```
这样就可以将一个HashMap<String, List<String>>中的value值赋值给Item有两行字的ListView了。
阅读全文