gpt4 book ai didi

java - 将 Hashmap 数组添加到 Listview

转载 作者:行者123 更新时间:2023-11-29 21:30:43 26 4
gpt4 key购买 nike

我是 Android 编程的初学者,我在完成这个简单的任务时遇到了很多麻烦。

我有一个数组列表:

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

我想将每个键/值对添加到 ListView。

如何将它们添加到 ListView?我在网上看到了无数关于使用适配器的解释,但它们都使用了我一无所知的变量。

最佳答案

构建您自己的适配器类:

public class MyAdapter extends BaseAdapter {

private Activity activity;
private HashMap<String, String> map;

public MyAdapter(Activity activity, HashMap<String, String> map) {
this.activity = activity;
this.map = map;
}

public int getCount() {
return map.size();
}

public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.my_list_item,
null);
}

// Recommended to use a list as the dataset passed in the constructor.
// Otherwise not sure how you going to map a position to an index in the dataset.
String key = // get a key from the HashMap above
String value = map.get(key);

TextView keyView = convertView.findViewById(R.id.item_key);
keyView.setText(key);

TextView valueView = convertView.findViewById(R.id.item_value);
valueView .setText(value);

return convertView;
}
}

然后,将其传递给您的 ListView setAdapter 方法:

MyAdapter myAdapter = new MyAdapter(this, map);
ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(myAdapter);

示例布局/my_list_item.xml:

<LinearLayout xmlns:android:http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<TextView
android:id="@+id/item_key"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/item_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>

关于java - 将 Hashmap 数组添加到 Listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19625607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com