1

En el ActionBar necesito implementar un AlertDialog con múltiples opciones el cual se llene por medio de un ArrayList con un Array Adapter, y los datos yo los obtengo desde un WebService implementando la clase AsyncTask.

Necesito que me expliquen o ayude a decirme como implemento ese AlertDialog, por el momento tengo un AlertDialog en la pantalla que necesito con los datos de prueba que yo ingrese, pero necesito llenarlo con los datos de mi WebService.

Anexo la imagen del AlertDialog.

Por cierto como extra necesito obtener los datos que el usuario marca y manejarlos en la Activity.

Agrego código mi menusetting donde tengo icono que uso para abrir mi 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>

Código donde Creo el AlertDialog con los datos ficticios

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

Código donde mando a llamar el diálogo

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

Código donde mando a llamar el método que necesito el cual contiene la información que llenará el alertdialog, ahora solo tengo la construcción de la clase

 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{

            }
        }
    }

Nuevo código

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

Screen

4
  • Agrega el código. el 1 jun. 2016 a las 20:54
  • ok, gracias por el comentario lo tomare en cuenta y una disculpa el 1 jun. 2016 a las 20:57
  • ya agregue el codigo el 1 jun. 2016 a las 21:07
  • Alguien que me pueda apoyar??? el 2 jun. 2016 a las 22:46

1 respuesta 1

1

Primeramente contestaré tu pregunta principal. Existen varias formas de realizarlo, puede ser un DialogFragment, pero veo que tienes una especie de settings a definir, aquí podría ser un Preference Activity o un Activity, el es punto importante es el tema, para poder tener un background con cierta opacidad.

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

Este tema lo agregarías a tu Activity dentro del AndroidManifest.xml:

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

Para lograr obtener algo como:

introducir la descripción de la imagen aquí

En cuanto a los datos, veo que los obtienes en el AsyncTask y la variable es: ZonaArrayList y la cual si la defines como global en tu Activity, puedes asignarla en esta linea, copiando el contenido de ZonaArrayList en colorsList y también convertir el ArrayList a un Array llamado 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();
            }
        });

....
....
12
  • hola, ya agregue mi codigo, gracias por lo del theme pero ahora si que mi duda es como llego mi alert dialog con mis datos que bienen de un webservices? el 1 jun. 2016 a las 21:10
  • gracias... o alguna propuesta mejor de como lo puedo aplicar no estoy cerrado, yo lo tengo pensado hacer asi por que he usado los alertdialog el 1 jun. 2016 a las 21:20
  • Listo, con respecto a los datos copia el contenido de tu ArrayList ZonaArrayList a colorsList con eso se veran los datos en tu Dialogo.
    – Jorgesys
    el 1 jun. 2016 a las 21:46
  • no esos son datos de pruebas como genero un string de prueba de colores solo para ver como se visualizara los datos en el alertdialog el 1 jun. 2016 a las 21:52
  • ArrayList<Zona> ZonaArrayList = new ArrayList<Zona>(); este es mi array que debo de usar ya que tengo una clase llamada Zona el 1 jun. 2016 a las 21:55

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.