在实际工作过程中,单单使用AlertDialog的单选功能不一定能满足我们的需求,需要绑定数据到 listview
1. 自定义Layout
LayoutInflater factory = LayoutInflater.from(DialogActivity.this);
final View view = factory.inflate(R.layout.linerlayout, null); 2,构造数据
List<Map<String, String>> nameList = new ArrayList<Map<String, String>>();//建立一个数组存储listview上显示的数据
for (int m = 0; m < 15; m++) {//initData为一个list类型的数据源
Map<String, String> nameMap = new HashMap<String, String>();
nameMap.put("name", "name"+m);
nameMap.put("id", m+"");
nameList.add(nameMap);
} 3ListView数据绑定
listView= (ListView) view.findViewById(R.id.lv_list); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
SimpleAdapter adapter = new SimpleAdapter(DialogActivity.this,
nameList, R.layout.item,
new String[] { "name","id" },
new int[] { R.id.tv1 ,R.id.tv2});
listView.setAdapter(adapter); 4.AlertDialog 绑定
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("选择姓名").setView(view)//在这里把写好的这个listview的布局加载dialog中
.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
}).create();
dialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
dialog.show();
5. LIstview 点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {//响应listview中的item的点击事件 @Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.d("TAG","ok");
// TODO Auto-generated method stub
TextView btn = (TextView) arg1 .findViewById(R.id.tv2);//取得每条item中的textview控件
// et_name.setText(tv.getText().toString()); Log.d("TAG",btn.getText().toString());
// dialog.cancel();
}
});