首页 > 解决方案 > 在片段中使用 hashmap 和简单适配器

问题描述

我正在尝试使用哈希图通过我正在制作的练习应用程序中的片段在列表视图中显示一些数据。哈希图以前可以工作,但是当我切换到片段时,我遇到了错误。现在我正在使用片段,是否需要以某种方式重写它?

我已经附上了我遇到问题的代码但是我在新的 SimpleAdapter 的括号中收到了错误标志

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(layout.home_fragment, null);

    ListView recipesListView = (ListView) view.findViewById(id.recipesListView);

    HashMap<String, String> recipes = new HashMap<>();
    recipes.put("Bangers and Mash", "Sausages, Potatoes, Gravy \n\nCook the sausages in a pan and boil the potatoes then mash them put on a plate and pur gravy on them");
    recipes.put("Spaghetti Carbonara", "Bacon, Onions, Spaghetti, Eggs, Cream \n\nCook bacon, onions in a pan and boil spaghetti, once cooked pour in eggs and cook on high until ready");
    recipes.put("Chicken and Bacon Sandwich", "Chicken, Bacon, Mayonnaise, Lettuce, Bread, Butter\n\nButter the bread and spread mayonnaise on it. Put the chicken and bacon between the bread");

    List<HashMap<String, String>> listRecipes = new ArrayList<>();
    SimpleAdapter adapter = new SimpleAdapter(this, listRecipes, layout.list_items,
            new String[]{"First Line", "Second Line"},
            new int[]{R.id.recipeTitle, R.id.method});

    Iterator it = recipes.entrySet().iterator();
    while (it.hasNext()) {
        HashMap<String, String> resultsMap = new HashMap<>();
        Map.Entry pair = (Map.Entry) it.next();
        resultsMap.put("First Line", pair.getKey().toString());
        resultsMap.put("Second Line", pair.getValue().toString());
        listRecipes.add(resultsMap);
    }

    recipesListView.setAdapter(adapter);
    return view;
}


}

}

感谢您提供的任何帮助。

标签: javaandroidandroid-fragments

解决方案


推荐阅读