Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

android - Multiple choice AlertDialog with custom Adapter

I am trying to create a AlertDialog with multiple choice option. I have tried with the setMultiChoiceItems but what i have is a ArrayList<Category> and not a CharSequence so i tried with the adapter.

The problem with setAdapter is that when i select one item it closes the dialog window. And what i want is to select the items and then hit the OK button to see what items where selected.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Pick a color");
        ArrayAdapter<Category> catsAdapter = new ArrayAdapter<Category>(this, android.R.layout.select_dialog_multichoice,this.categories);
        builder.setAdapter(catsAdapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {

            }
        });
        builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                //do something  
               }                
        });;

        AlertDialog alert = builder.create();
        alert.show();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, there doesn't seem to be an easy way to toggle on AlertDialog's multichoicemode without calling setMultiChoiceItems().

However, you can set an adapter, then turn on multichoice mode in the contained ListView itself.

final AlertDialog dialog = new AlertDialog.Builder(getActivity())
    .setTitle("Title")
    .setAdapter(yourAdapter, null)
    .setPositiveButton(getResources().getString(R.string.positive), null)
    .setNegativeButton(getResources().getString(android.R.string.cancel), null)
    .create();

dialog.getListView().setItemsCanFocus(false);
dialog.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
dialog.getListView().setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        // Manage selected items here
        System.out.println("clicked" + position);
        CheckedTextView textView = (CheckedTextView) view;
        if(textView.isChecked()) {

        } else {

        }
    }
});

dialog.show();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...