【问题标题】:How Do I Control on MultiChoice AlertDialog如何控制 MultiChoice AlertDialog
【发布时间】:2015-09-01 04:34:50
【问题描述】:

我在我的应用程序中使用对话框来允许用户进行多项选择,这是我的代码:

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

我有两个疑问:

  1. 就像我选择了红色和紫色

    (然后在 TextView 中得到这样的输出:Red, Purple,

    首先我想删除逗号(最后一个值)

  2. 我已经选择了红色和紫色,当我再次打开对话框时,默认情况下没有选择红色和紫色(如何保存状态)enter code here,因此,当我再次选择这些时(红色和紫色)​​两个项目,每个项目在 TextView 中两次

【问题讨论】:

    标签: android android-alertdialog multichoiceitems


    【解决方案1】:

    请尝试这样做并改进代码结构,以便对其进行有效管理。

    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;
            }
        }
    

    解决了您的所有疑问:

    1。就像我选择了红色和紫色

    => 检查元素的索引,如果是最后一个则不要附加逗号。

    2。我已经选择了红色和紫色,当我再次打开对话框时,默认情况下没有选择红色和紫色(如何保存状态)

    => 在默认数组中使用 vo 保存状态。它将一直保存到您的 Activity 未被破坏为止。

    3。当我再次选择这两个项目(红色和紫色)​​时,在 TextView 中获取每个项目两次

    => 清除列表,以免值重复。

    【讨论】:

    • 毫无疑问@MamataGelanee,您已经为我的要求提供了出色而完整的解决方案......但老板的解决方案也很好......对我来说,你们都提供了最好的答案......所以我不能接受你的解决方案,因为我已经接受了老板的,但我觉得很有用......
    • 你能帮我创建分步视图吗——比如第 1 步表单 > 第 2 步表单和第 3 步(完成)
    • 就像在许多应用程序中创建帐户或预约或预订房间一样,我们必须填写三种不同的表格(第 1 步 - 个人资料)>(第 2 步 - 预订)>(第 3 步:审查细节)我希望你现在能理解我的要求@MamataGelanee
    • 我运气不好几天前 practo 正在使用,但现在他们删除了它.. 我正在寻找更清晰的图像
    【解决方案2】:

    尝试在循环后更新您的文本视图

    如果您的循环迭代达到checkedcolors 的长度,则不要附加逗号。

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

    你的 textview 只会更新一次,所以你不会在 TextView 中获得每个项目两次。

    要保存状态,您必须使用SharedPreference

    为了保存到偏好使用这个

           SharedPreferences preferences = mContext.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
    
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("yourColor",isChecked);
            editor.commit();
    

    然后检索

            boolean isChecked = preferences.getBoolean("yourColor");
    

    【讨论】:

    • @Oreo 很高兴我能帮上忙 :)
    • 你能帮我创建分步视图吗——比如第 1 步表单 > 第 2 步表单和第 3 步(完成)?
    • @Oreo 实现SharedPreference的步骤??
    • no @Boss 就像在许多应用程序中创建帐户或预约或预订房间一样,我们必须填写三种不同的表格(第 1 步 - 个人资料)>(第 2 步 - 预订)> ( Step 3 : Review Detail) 我希望你现在能理解我的要求
    • @Oreo 你发现实现它的问题是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2015-07-14
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多