如何使用自定义视图显示单选AlertDialog?

时间:2012-11-25 20:12:50

标签: android listview alertdialog

我需要单独选择自定义AlertDialog,但没有单选按钮,每个项目中有两个自定义TextView。我尝试使用AlertDialog:

ArrayList<HashMap<String,String>> items=new ArrayList<HashMap<String,String>>();
//..here I fill my ArrayList
SimpleAdapter simpleAdapter=new SimpleAdapter(this, items, R.layout.list_item, new String[] {"name","count"}, new int[] {R.id.name,R.id.count});

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setSingleChoiceItems(simpleAdapter, -1, new OnClickListener() {
    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        //Here I handle click
    }});
alert.show();

但点击项目后它没有关闭。为什么?我可以解决它吗?

或者,我尝试使用Dialog:

ArrayList<HashMap<String,String>> items=new ArrayList<HashMap<String,String>>();
//..here I fill my ArrayList
SimpleAdapter simpleAdapter=new SimpleAdapter(this, items, R.layout.list_item, new String[] {"name","count"}, new int[] {R.id.name,R.id.count});

Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

View view=LayoutInflater.from(this).inflate(R.layout.items_list, null);
ListView listView=(ListView) view.findViewById(R.id.list_view);
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        //Here I handle click
        dialog.dismiss();
    }});

dialog.setContentView(view);
dialog.show();

但它有样式问题,文字没有显示(文字颜色与背景颜色一致)。

我认为AlertDialog最适合我。但是怎么做呢?

1 个答案:

答案 0 :(得分:2)

  

但点击项目后它没有关闭。为什么?我可以解决它吗?

AlertDialog.Builder.setSingleChoiceItems方法默认情况下不会关闭对话框,因此您必须手动执行此操作。为此,您只需将DialogInterface回调的onClick参数(代表对话框本身)转换为Dialog并使用dismiss()方法:

((Dialog) arg0).dismiss();