Android HashMap到ListView

Android HashMap到ListView,android,listview,hashmap,Android,Listview,Hashmap,我有HashMap,如何将其放在ListView中?需要使用哪个适配器 public void showCinemas(HashMap<String, String> cinemas) { ...//What? list.setAdapter(adapter); } 公共影院(HashMap影院) { ……什么? list.setAdapter(适配器); } 很简单: 对于你将要创建的列表项,例如,假设你必须将学生的记录放在诸如姓名和地址之类的列表项中 p

我有HashMap,如何将其放在ListView中?需要使用哪个适配器

    public void showCinemas(HashMap<String, String> cinemas)
{
    ...//What?
    list.setAdapter(adapter);
}
公共影院(HashMap影院)
{
……什么?
list.setAdapter(适配器);
}
很简单:

对于你将要创建的列表项,例如,假设你必须将学生的记录放在诸如姓名和地址之类的列表项中

private HashMap<String,Object> prepareListViewItems(Student[] student)
{
 ArrayList<HashMap<String,Object>> listdata = new ArrayList<HashMap<String,Object>>();

for(int index=0;index<student.size();index++)
{
    HashMap<String,Object> data = new HashMap<String,Object>();
    data.put("roll", student[indxe].roll);
    data.put("address", student[indxe].address);
    data=null;
    listdata.add(data);

}

return data;
}

private void setListAdapter(Student[] students)
{
    TestListAdapter adapter = new TestListAdapter(prepareListViewItems(students))
    list.setAdapter(adapter);
}
private HashMap prepareListViewItems(学生[]学生)
{
ArrayList listdata=新的ArrayList();

对于(int index=0;index生成简单适配器类):

MyAdapter.java

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Map;

public class MyAdapter extends BaseAdapter {
    private final ArrayList mData;

    public MyAdapter(Map<String, String> map) {
        mData = new ArrayList();
        mData.addAll(map.entrySet());
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Map.Entry<String, String> getItem(int position) {
        return (Map.Entry) mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO implement you own logic with ID
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View result;

        if (convertView == null) {
            result = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter_item, parent, false);
        } else {
            result = convertView;
        }

        Map.Entry<String, String> item = getItem(position);

        // TODO replace findViewById by ViewHolder
        ((TextView) result.findViewById(android.R.id.text1)).setText(item.getKey());
        ((TextView) result.findViewById(android.R.id.text2)).setText(item.getValue());

        return result;
    }
}
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.BaseAdapter;
导入android.widget.TextView;
导入java.util.ArrayList;
导入java.util.Map;
公共类MyAdapter扩展了BaseAdapter{
私有最终ArrayList mData;
公共MyAdapter(映射){
mData=newarraylist();
mData.addAll(map.entrySet());
}
@凌驾
public int getCount(){
返回mData.size();
}
@凌驾
公共映射。条目getItem(int位置){
返回(Map.Entry)mData.get(position);
}
@凌驾
公共长getItemId(int位置){
//TODO使用ID实现您自己的逻辑
返回0;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
最终查看结果;
if(convertView==null){
结果=LayoutInflater.from(parent.getContext()).flate(R.layout.my_adapter_项,parent,false);
}否则{
结果=转换视图;
}
Map.Entry item=getItem(位置);
//TODO用ViewHolder替换findViewById
((TextView)result.findviewbyd(android.R.id.text1)).setText(item.getKey());
((TextView)result.findviewbyd(android.R.id.text2)).setText(item.getValue());
返回结果;
}
}
layout/my\u adapter\u item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

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

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

您的代码:

public void showCinemas(HashMap<String, String> cinemas) {
    MyAdapter adapter = new MyAdapter(cinemas);
    list.setAdapter(adapter);
}
private Map<String, Object> mMapItems;                      // original data source of all items
private List<Map.Entry<String, Object>> mListOfMapEntries;  // list of entries from mMapItems
private MapEntryListAdapter mMapEntryListAdapter;
公共影院(HashMap影院){
MyAdapter=新的MyAdapter(电影院);
list.setAdapter(适配器);
}

HashMap由2个集合(或更好的1个集合和1个集合)组成,因此扩展ArrayAdapter实际上是不可能的;但您可以轻松获得Map.Entry的集合(或更好的一个集合),并将其转换为列表:

发件人:


这与上面Zanna的答案有一些相似之处,但更干净、更完善、更全面。我认为这是最简单的

适配器

public class MapEntryListAdapter extends ArrayAdapter<Map.Entry<String, Object>>
{
    public MapEntryListAdapter (Context context, List<Map.Entry<String, Object>> entryList)
    {
        super (context, android.R.layout.simple_list_item_2, entryList);
    }

    @NonNull @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        View currentItemView = convertView != null ? convertView :
                       LayoutInflater.from (getContext ()).inflate (
                               android.R.layout.simple_list_item_2, parent, false);

        Map.Entry<String, Object> currentEntry = this.getItem (position);

        TextView textViewKey = currentItemView.findViewById (android.R.id.text1);
        TextView textViewValue = currentItemView.findViewById (android.R.id.text2);

        textViewKey.setText (currentEntry.getKey ());
        textViewValue.setText (currentEntry.getValue ().toString ());

        return currentItemView;
    }
}
这会清除所有现有项的列表,然后将映射中的项添加到列表中,非常重要的是,会告诉适配器更新ListView


(注意:不要在此处创建新的列表对象(与此处显示的清除和添加相反),因为这样您将不再修改适配器的数据源,该数据源仍将指向原始列表。)

他需要在
ListView
中显示键值对,因此
HashMap
ArrayList
将不起作用。如果您在向listdata添加数据之前设置
data=null;
,您总是向listdata添加null。我错了吗?什么意思是“只有数组才足够?”胡说八道。请看下面的完整答案。在这种情况下,我维护自己的hashmap,但不需要数组。太好了!!我正在从json中提取一个电视频道列表:图像、名称和编号。图像使用获取的URL和一个自包含的图像下载器类加载。如果您可能需要它,请告诉我,我很高兴与您共享。它不应该是值()而不是entrySet?如何处理此问题?我建议以后参考将entrySet()更改为values(),正如@cafebabe1991;)所建议的那样有时我会注意到这个问题并阅读下面的注释,我认为重写ArrayAdapter比重写BaseAdapter更简单。这样,您就不必重写ArrayAdapter已经包含的方法,如getItem()和getCount().Upvote用于提及LinkedHashMap。HashMap有一些自动排序问题。经过长时间的尝试,这是唯一有效的方法!谢谢。
class HashMapArrayAdapter extends ArrayAdapter {

        private static class ViewHolder {
            TextView tV1;
            TextView tV2;
        }

        public HashMapArrayAdapter(Context context, int textViewResourceId, List<Map.Entry<String, Object>> objects) {
            super(context, textViewResourceId, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder;

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.tV1 = (TextView) convertView.findViewById(android.R.id.text1);
                viewHolder.tV2 = (TextView) convertView.findViewById(android.R.id.text2);
                convertView.setTag(viewHolder);
            } else
                viewHolder = (ViewHolder) convertView.getTag();

            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) this.getItem(position);

            viewHolder.tV1.setText(entry.getKey());
            viewHolder.tV2.setText(entry.getValue().toString());
            return convertView;
        }
 ArrayAdapter adapter = new HashMapArrayAdapter(this.getActivity(), android.R.layout.simple_list_item_2, new ArrayList(map.entrySet()));
public class MapEntryListAdapter extends ArrayAdapter<Map.Entry<String, Object>>
{
    public MapEntryListAdapter (Context context, List<Map.Entry<String, Object>> entryList)
    {
        super (context, android.R.layout.simple_list_item_2, entryList);
    }

    @NonNull @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        View currentItemView = convertView != null ? convertView :
                       LayoutInflater.from (getContext ()).inflate (
                               android.R.layout.simple_list_item_2, parent, false);

        Map.Entry<String, Object> currentEntry = this.getItem (position);

        TextView textViewKey = currentItemView.findViewById (android.R.id.text1);
        TextView textViewValue = currentItemView.findViewById (android.R.id.text2);

        textViewKey.setText (currentEntry.getKey ());
        textViewValue.setText (currentEntry.getValue ().toString ());

        return currentItemView;
    }
}
private Map<String, Object> mMapItems;                      // original data source of all items
private List<Map.Entry<String, Object>> mListOfMapEntries;  // list of entries from mMapItems
private MapEntryListAdapter mMapEntryListAdapter;
    mMapItems = new LinkedHashMap<> ();

    mMapItems.put ("Test Key", "Test Value");                       // put in sample item #1
    mMapItems.put ("Sample Key", "Sample Value");                   // put in sample item #2

    mListOfMapEntries = new ArrayList<> (mMapItems.entrySet ());    // create the list

    mMapEntryListAdapter = new MapEntryListAdapter (this, mListOfMapEntries);

    ListView listView = findViewById (R.id.list_view);
    listView.setAdapter (mMapEntryListAdapter);
    mListOfMapEntries.clear ();
    mListOfMapEntries.addAll (mMapItems.entrySet ());
    mMapEntryListAdapter.notifyDataSetChanged ();