我正在尝试创建一个非常基本的ListView对话框,其中每个项目都有一个子标题。为此,我正在尝试将simple_list_item_2布局与List(Map(String,String))的适配器一起使用。代码如下:
public static class StoreList extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
// Dummy data
Map<String, String> datum = new HashMap<String, String>();
datum.put("name", "Name1");
datum.put("address", "USA");
data.add(datum);
Map<String, String> datum2 = new HashMap<String, String>();
datum.put("name", "Name2");
datum.put("address", "CAN");
data.add(datum2);
// Adapter for the ListView:
SimpleAdapter adapter = new SimpleAdapter(
getActivity(),
data,
android.R.layout.simple_list_item_2,
new String[] {"name", "address"},
new int[] {android.R.id.text1, android.R.id.text2});
// Listener for the ListView:
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getActivity(), StoreActivity.class);
Map<String, String> listItem = data.get(which);
i.putExtra("name", listItem.get("name"));
i.putExtra("address", listItem.get("address"));
startActivity(i);
}
};
// Build the ListView dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.storeListTitle);
builder.setAdapter(adapter, listener);
return builder.create();
}
}
执行时,结果如下:
http://i.imgur.com/8gkTECe.png
如您所见,只显示四个文本字符串中的一个。这是怎么回事?
答案 0 :(得分:1)
您在基准面而不是基准面上设置值。
// Dummy data
Map<String, String> datum = new HashMap<String, String>();
datum.put("name", "Name1");
datum.put("address", "USA");
data.add(datum);
Map<String, String> datum2 = new HashMap<String, String>();
datum.put("name", "Name2"); //should be datum2
datum.put("address", "CAN"); //should be datum2
data.add(datum2);