BArtWell
BArtWell

Reputation: 4044

How to display single choice AlertDialog with custom views?

I need to make custom AlertDialog with single choice, but without radio buttons and with two custom TextViews in each item. I've try to use 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();

But it doesn't close after click on item. Why? May be I can fix it?

Alternatively, I've try to use Dialog for it:

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();

But it have problem with styles and text doesn't showing (text color coincide with background color).

I think that AlertDialog preferably for me. But how to make it?

Upvotes: 2

Views: 6442

Answers (1)

user
user

Reputation: 87064

But it doesn't close after click on item. Why? May be I can fix it?

The AlertDialog.Builder.setSingleChoiceItems method will not dismiss the dialog by default so you have to do it manually. To do this, you just need to cast the DialogInterface parameter of the onClick callback(representing the dialog itself) to a Dialog and use the dismiss() method:

((Dialog) arg0).dismiss();

Upvotes: 2

Related Questions