Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Control on MultiChoice AlertDialog

I am using Dialog in my app to allow user to make multiple selection, Here is my code:

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Build an AlertDialog
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            // String array for alert dialog multi choice items
            String[] colors = new String[]{
                    "Red",
                    "Green",
                    "Blue",
                    "Purple",
                    "Olive"
            };

            // Boolean array for initial selected items
            final boolean[] checkedColors = new boolean[]{
                    false, // Red
                    false, // Green
                    false, // Blue
                    false, // Purple
                    false // Olive

            };

            // Convert the color array to list
            final List<String> colorsList = Arrays.asList(colors);

            // Set multiple choice items for alert dialog

            builder.setMultiChoiceItems(colors, checkedColors, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                    // Update the current focused item's checked status
                    checkedColors[which] = isChecked;

                    // Get the current focused item
                    String currentItem = colorsList.get(which);

                    // Notify the current action
                    Toast.makeText(getApplicationContext(),
                            currentItem + " " + isChecked, Toast.LENGTH_SHORT).show();
                }
            });

            // Specify the dialog is not cancelable
            builder.setCancelable(false);

            // Set a title for alert dialog
            builder.setTitle("Your preferred colors?");

            // Set the positive/yes button click listener
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Do something when click positive button
                    tv.setText("Your preferred colors..... \n");
                    for (int i = 0; i<checkedColors.length; i++){
                        boolean checked = checkedColors[i];
                        if (checked) {
                            tv.setText(tv.getText() + colorsList.get(i) + ", ");
                        }
                    }
                }
            });

            // Set the negative/no button click listener
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Do something when click the negative button
                }
            });

            // Set the neutral/cancel button click listener
            builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Do something when click the neutral button
                }
            });

            AlertDialog dialog = builder.create();
            // Display the alert dialog on interface
            dialog.show();
        }
    });

And I have two queries:

  1. Like I have selected Red and Purple

    (then in TextView getting output like this: Red, Purple,)

    First of all I would like to remove comma (which getting with last value)

  2. I already selected Red and Purple, when i again open dialog not getting red and purple as selected by default (How can i save the state)enter code here, and as a result, when i am again selecting these (Red and Purple) two items, getting each item twice in a TextView

like image 733
Oreo Avatar asked Sep 01 '15 04:09

Oreo


People also ask

How do I add an image to AlertDialog?

setView(imageView); alert. setNeutralButton("Here!", new DialogInterface. OnClickListener() { public void onClick(DialogInterface dlg, int sumthin) { } }); alert.

How to show AlertDialog in Kotlin?

To set the action on alert dialog call the setPositiveButton(), setNeutralButton() and setNegativeButton() methods for positive, neutral and negative action respectively. The show() method of AlertDialog. Builder is used to display the alert dialog.

How to create AlertDialog in Kotlin?

Create an AlertDialog Builder using the activity's context. Set message content using the builder. Set Positive Button Text and Action to be taken when the button is clicked using the builder. Set Negative Button Text and Action to be taken when the button is clicked using the builder.


2 Answers

Try updating your textview after the loop

And if your loop iteration reaches the length of the checkedcolors then donot append a comma.

public void onClick(DialogInterface dialog, int which) {
        // Do something when click positive button
        tv.setText("Your preferred colors..... \n");
        for (int i = 0; i < checkedColors.length; i++) {
            boolean checked = checkedColors[i];
            String colors = "";
            if (checked) {
                colors = colors + colorsList.get(i) ;
                if (i != checkedColors.length - 1) {
                    colors = colors + ", ";
                }
            }
        }
        tv.setText(tv.getText() + colors);
    }

Yor textview will be updated only once, so you wont be getting each item twice in the TextView.

For saving the state you have to use SharedPreference.

For saving into preference use this

       SharedPreferences preferences = mContext.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("yourColor",isChecked);
        editor.commit();

And to retrieve

        boolean isChecked = preferences.getBoolean("yourColor");
like image 89
Emil Avatar answered Oct 24 '22 00:10

Emil


Please try this and improve structure of your code so that it can be managed efficiently.

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private TextView txtSelected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn_dialog);
        txtSelected = (TextView) findViewById(R.id.txt_selected);

        final ArrayList<ColorVO> colorList = new ArrayList<ColorVO>();
        // String array for alert dialog multi choice items
        final String[] colors = new String[]{
                "Red",
                "Green",
                "Blue",
                "Purple",
                "Olive"
        };
        // Boolean array for initial selected items
        final boolean[] checkedColors = new boolean[]{
                false, // Red
                false, // Green
                false, // Blue
                false, // Purple
                false // Olive

        };

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                // make a list to hold state of every color
                for (int i = 0; i < colors.length; i++) {
                    ColorVO colorVO = new ColorVO();
                    colorVO.setName(colors[i]);
                    colorVO.setSelected(checkedColors[i]);
                    colorList.add(colorVO);
                }

                // Do something here to pass only arraylist on this both arrays ('colors' & 'checkedColors')
                builder.setMultiChoiceItems(colors, checkedColors, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        // set state to vo in list
                        colorList.get(which).setSelected(isChecked);
                        Toast.makeText(getApplicationContext(),
                                colorList.get(which).getName() + " " + isChecked, Toast.LENGTH_SHORT).show();
                    }
                });

                builder.setCancelable(false);

                builder.setTitle("Your preferred colors?");

                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        txtSelected.setText("Your preferred colors..... \n");

                        // save state of selected vos
                        ArrayList<ColorVO> selectedList = new ArrayList<>();
                        for (int i = 0; i < colorList.size(); i++) {
                            ColorVO colorVO = colorList.get(i);
                            colors[i] = colorVO.getName();
                            checkedColors[i] = colorVO.isSelected();
                            if (colorVO.isSelected()) {
                                selectedList.add(colorVO);
                            }
                        }

                        for (int i = 0; i < selectedList.size(); i++) {
                            // if element is last then not attach comma or attach it
                            if (i != selectedList.size() - 1)
                                txtSelected.setText(txtSelected.getText() + selectedList.get(i).getName() + " ,");
                            else
                                txtSelected.setText(txtSelected.getText() + selectedList.get(i).getName());
                        }
                        colorList.clear();
                    }
                });

                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // make sure to clear list that duplication dont formed here
                        colorList.clear();
                    }
                });

                builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // make sure to clear list that duplication dont formed here
                        colorList.clear();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }

    private class ColorVO {
        private String name;
        private boolean selected;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

Solved all of your queries :

1. Like I have selected Red and Purple

=> Check for index of element, If it is last then do not attach comma.

2. I already selected Red and Purple, when i again open dialog not getting red and purple as selected by default (How can i save the state)

=> save state using vo in your default array.It will be saved until your activity is not destroyed.

3. when i am again selecting these (Red and Purple) two items, getting each item twice in a TextView

=> Clear list so that values do not get duplicated.

like image 29
AndiGeeky Avatar answered Oct 24 '22 00:10

AndiGeeky