我是 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>