首页 > 解决方案 > 关于Adapter类如何从HashMap中获取key和value

问题描述

在我的RecyclerViewAdapter课堂上,我作为数据传递HashMap<String,ArrayList<Custom>>,现在我想获取每个位置的键和值,但我不知道我应该怎么做!提前致谢

public class Main_Recycler_Single_Row extends RecyclerView.Adapter<Main_Recycler_Single_Row.ViewHolder> {



private Context mContext;
private HashMap<String,ArrayList<Products>> dataSet;

public Main_Recycler_Single_Row(Context mContext, HashMap<String,ArrayList<Products>> mDataSet) {
    this.mContext = mContext;
    this.dataSet = mDataSet;

} @Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

    Map.Entry<String,ArrayList<Products>> entry=(Map.Entry<String,ArrayList<Products>>) dataSet.entrySet();//this line is my problem!


    holder.header.setText(entry.getKey());

    holder.mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
    holder.mRecyclerView.setHasFixedSize(true);
    holder.mRecyclerView.setAdapter(new Main_Recycler_Sinle_Item(mContext,entry.getValue()));

}

标签: androidhashmap

解决方案


如果你想ValueHashMapusing中获得position,你还需要Array维护keys

keys = (String[])mDataSet.keySet().toArray();

您的ViewHolder课程将如下所示:

public Main_Recycler_Single_Row(Context mContext, HashMap<String,ArrayList<Products>> mDataSet) {
    this.mContext = mContext;
    this.dataSet = mDataSet;
    keys = (String[])mDataSet.keySet().toArray();

} @Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {

    holder.header.setText(keys[position]);

    holder.mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
    holder.mRecyclerView.setHasFixedSize(true);
    holder.mRecyclerView.setAdapter(new Main_Recycler_Sinle_Item(mContext,dataSet.get(keys[position])));

}

推荐阅读