我目前在片段中实现listview时遇到问题。 我使用Hashmap然后转换为arrayList,如下所示:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View myView = inflater.inflate(
R.layout.fragment_portfolio, container, false);
ListView listview = (ListView) myView.findViewById(R.id.listview);
List<HashMap<String, Integer>> fillMaps = new ArrayList<>();
HashMap<String, Integer> portfoliodata = new HashMap<>();
portfoliodata.put("Test", 23);
fillMaps.add(portfoliodata);
SimpleAdapter adapter = new SimpleAdapter(getActivity().getApplicationContext(), fillMaps, R.layout.my_adapter_item, new String[] { "AAA","BBB" },
new int[] { android.R.id.text1, android.R.id.text2 });
listview.setAdapter(adapter);
return myView;
}
然而,结果总是一个完全空白的片段。知道为什么会这样做以及如何解决这个问题?
提前谢谢
答案 0 :(得分:1)
getActivity(),因为您还没有Activity的上下文。
您可以探测将代码移动到onResume()方法。
*请记住,您必须使用数据连接每一列,如下所示:
ListView listview;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(
R.layout.fragment_portfolio, container, false);
listview = (ListView) myView.findViewById(R.id.listview);
return myView;
}
@Override
public void onResume() {
// create the grid item mapping
String[] from = new String[] {"AAA","BBB"};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
List<HashMap<String, String>> fillMaps = new ArrayList<>();
HashMap<String, String> portfoliodata = new HashMap<>();
portfoliodata.put("AAA", "Text SampleA");
portfoliodata.put("BBB", "Text SampleB");
fillMaps.add(portfoliodata);
SimpleAdapter adapter = new SimpleAdapter(getActivity(), fillMaps,
R.layout.my_adapter_item, from, to);
listview.setAdapter(adapter);
}
祝你好运!