Create MultiChoice AlertDialog on Android

1

In ActionBar I need to implement a AlertDialog with multiple options which is filled by means of a ArrayList with an Array Adapter, and the data I get from a WebService implementing the class AsyncTask .

I need you to explain or help me tell me how to implement that AlertDialog , for the moment I have a AlertDialog on the screen that I need with the test data that I enter, but I need to fill it with the data of my WebService.

Annex the image of AlertDialog .

Incidentally, as an extra, I need to obtain the data that the user has marked and manage it in the Activity.

I add code my menusetting where I have an icon that I use to open my alertdialog

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="mx.com.oncontrol.oncontrolmovile.Clientes">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="@string/action_search"
        android:hint="Buscar Cliente"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always"/>

    //item que uso para Alertdialog
    <item
        android:id="@+id/action_favorite"
        android:icon="@drawable/filtro"
        android:title="@string/filtro"
        app:showAsAction="ifRoom"/>

</menu>

Code where I create the AlertDialog with the fictitious data

public void EligirZona(){

    AlertDialog.Builder builder = new AlertDialog.Builder(Clientes.this);{
        Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        // String array for alert dialog multi choice items
        String[] colors = new String[]{
                "Norte",
                "Sur",
                "Metropolitana",

        };

        // Boolean array for initial selected items
        final boolean[] checkedColors = new boolean[]{
                false, // Norte
                true, // Sur
                false, // Metropolitana
        };

        // Convert the color array to list
        final List<String> colorsList = Arrays.asList(colors);
        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("Selecciona la Zona(s) que Visitaras");

        // 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("La Zona Seleccionada es..... \n");
                for (int i = 0; i<checkedColors.length; i++){
                    boolean checked = checkedColors[i];
                    if (checked) {
                        tv.setText(tv.getText() + colorsList.get(i) + "\n");
                    }
                }*/
                Toast.makeText(getApplicationContext(),"La Zona Seleccionada es", Toast.LENGTH_SHORT);
            }
        });

        // 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
                dialog.cancel();
            }
        });

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

Code where I call the dialogue

public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            // action with ID action_refresh was selected
            case R.id.action_favorite:
                /*SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
                AsyncZona task = new AsyncZona(settings.getString("ONControlWSURL", "").toString());
                //Call execute
                task.execute();*/
               EligirZona();
                break;


        }
        return super.onOptionsItemSelected(item);
    }

Code where I send to call the method that I need which contains the information that will fill the alertdialog , now I only have the construction of the class

 private class AsyncZona extends AsyncTask<String, ArrayList, ArrayList>
    {
        private String ONControlWSURL;
        public AsyncZona(String ONControlWSURL)
        {
            this.ONControlWSURL = ONControlWSURL;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            AlertDialog.Builder builder = new AlertDialog.Builder(Clientes.this);
        }

        @Override
        protected ArrayList doInBackground(String... params) {
            ZonaArrayList = new ArrayList<Zona>();
            webService O_WS = new webService(ONControlWSURL);
            ZonaArrayList=O_WS.Zona();
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList arrayList) {
            super.onPostExecute(arrayList);

            if(ZonaArrayList.size()!=0){

                /*Spinner spinner = (Spinner)findViewById(R.id.menu_spinner1);
                ArrayAdapter<FormaPago> adapter = new ArrayAdapter<FormaPago>(context, android.R.layout.simple_spinner_dropdown_item, PagoArrayList);
                spinner.setAdapter(adapter);*/

            }else{

            }
        }
    }

New code

 public void EligirZona() {

    AlertDialog.Builder builder = new AlertDialog.Builder(Clientes.this);
    {

        SharedPreferences settings = getSharedPreferences("ONC_Settings", 0);
        AsyncZona task = new AsyncZona(settings.getString("ONControlWSURL", "").toString());
        //Call execute
        task.execute();

        // Boolean array for initial selected items
        final boolean[] checkedColors = new boolean[]{
                false, // Norte
                true, // Sur
                false, // Metropolitana
        };

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

        String[] colors = new String[ZonaArrayList.size()];
        colors = ZonaArrayList.toArray(colors);


        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;

            }
        });

        builder.setCancelable(false);

        // Set a title for alert dialog
        builder.setTitle("Selecciona la Zona(s) que Visitaras");

        // 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("La Zona Seleccionada es..... \n");
            for (int i = 0; i<checkedColors.length; i++){
                boolean checked = checkedColors[i];
                if (checked) {
                    tv.setText(tv.getText() + colorsList.get(i) + "\n");
                }
            }*/
                Toast.makeText(getApplicationContext(),"La Zona Seleccionada es", Toast.LENGTH_SHORT);
            }
        });

        // 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
                dialog.cancel();
            }
        });

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

    
asked by Hugo Rodriguez 01.06.2016 в 22:30
source

1 answer

1

First I will answer your main question. There are several ways to do it, it can be a DialogFragment, but I see that you have a kind of settings to define, here it could be a Preference Activity or an Activity, the important point is the theme, to be able to have a background with some opacity.

<style name="CustomTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:colorBackground">#fff0f0f0</item>
    <item name="android:divider">#ffe0e0e0</item>
    <item name="android:textColorPrimary">#ff555555</item>
    <item name="android:textColorSecondary">#ff808080</item>
</style>

This topic would add it to your Activity within AndroidManifest.xml :

 <activity
            android:name=".MyActivity"
            android:theme="@style/CustomTheme"/>

To achieve something like:

Regarding the data, I see that you get it in the AsyncTask and the variable is: ZonaArrayList and which if you define it as global in your Activity, you can assign it in this line, copying the content of ZonaArrayList in colorsList and also convert the ArrayList to an array called colors:

public void EligirZona(){

    AlertDialog.Builder builder = new AlertDialog.Builder(Clientes.this);{
        Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        // String array for alert dialog multi choice items
       /* String[] colors = new String[]{
                "Norte",
                "Sur",
                "Metropolitana",

        }; */

        // Boolean array for initial selected items
        final boolean[] checkedColors = new boolean[]{
                false, // Norte
                true, // Sur
                false, // Metropolitana
        };

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

String[]   colors = new String[ZonaArrayList.size()];
 colors = ZonaArrayList.toArray(colors);


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

....
....
    
answered by 01.06.2016 в 22:48