Change list background color (AlertDialog) when selecting an option, and keep it when reopening

3

I have doubts about how to do a alertdialog custom, where I can make that when I select an item of the alertDialog when I reopen it has the background of another color, indicating that this item was selected, and if I select another item, that color and the previous item, return to its normal state ...

String[] lista = {"1","2","3","4","5"}

AlertDialog.Builder builder = new AlertDialog.Builder(activity_main_panel.this);
    builder.setTitle("titulo");
    builder.setItems(lista, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });


AlertDialog alert = builder.create();
alert.show();

Illustrative image:

    
asked by DarckBlezzer 06.09.2017 в 06:30
source

1 answer

0

This is an example also for those who had this problem, I hope it serves them all ...

Global Variables

//Solo va a ser alert.show en el botón
AlertDialog alert;
//Variable para saber cual es la opción seleccionada
int posicionSeleccionada =-1;

Function to declare everything that the list contains and not declare it more times ...

//Funcion que conlleva la creacion de ListAdapter, alertidalog.Builder y alertDialog
public void declararListView(){
    //custom, lista de contenidos aleatorios, podria mandarse a esta funcion la lista
    String[] lista = {"aeroplanos", "animales", "carros", "colores", "flores", "cartas", "mounstros", "numeros", "sombras", "sonrrisas", "deportes", "estrellas" };

    //se asigno un xml customisable, tambien se puede agregar una imagen a el.. o otras cosas
    ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_row, lista) {

        ViewHolder holder;

        class ViewHolder {
            TextView titulo;
        }

        @Override
        public int getPosition(@Nullable String item) {
            return super.getPosition(item);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            //si convertView es null, creamos su cuerpo
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_row, null);
                holder = new ViewHolder();
                holder.titulo = (TextView) convertView.findViewById(R.id.titulo);
                convertView.setTag(holder);

            } else {
                // vista definida, obtener la vista
                holder = (ViewHolder) convertView.getTag();
            }

            //poner texto a textview
            holder.titulo.setText(getItem(position));

            //declarar todos los textview y linearlayout a su color por default
                //cuerpo de textview - seria el linearlayout
                convertView.setBackgroundColor(0);
                //Cambiar color por defecto de textview, se debe especificar color
                holder.titulo.setTextColor(Color.BLACK);
                //hace clicleable el item
                convertView.setClickable(false);

            // si es la pocicion seleccionada, se cambia el color del cuerpo y del textview
            if(position == posicionSeleccionada){
                convertView.setBackgroundColor(Color.BLACK);
                holder.titulo.setTextColor(Color.WHITE);
                //hacer no clicleable el item
                convertView.setClickable(true);
            }

            return convertView;
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Lista");
    builder.setAdapter(adapter,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int itemPosicion) {

                    //obtenemos el texto directanente de DialogInterface, en vez de usar variable global...
                    ListView lw = ((AlertDialog)dialog).getListView();
                    Object checkedItem = lw.getAdapter().getItem(itemPosicion);

                    //imprimimos el texto de lo que se selecciono
                    System.out.println(checkedItem.toString());

                    //tambien se puede obtener texto del adapter, pasando la posicion
                    //adapter.getItem(i);

                    //asignamos la posicion a la variable global del item que se selecciono
                    posicionSeleccionada = itemPosicion;

                }
            });
    //boton negativo para cancelar
    builder.setNegativeButton("cancelar", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //cerrar lista
            dialogInterface.dismiss();
        }
    });

    alert = builder.create();
}

Function and button to call

//todo esto lo puse en onCreate
declararListView();

Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
      if(alert!=null)
          alert.show();
  }
});

File list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="20dp"
    android:paddingBottom="20dp"
    android:id="@+id/cuerpo"
    >
    <TextView
        android:id="@+id/titulo"
        android:textColor="#000000"
        android:text=""
        android:paddingLeft="10dip"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Sample images

  

Note: I hope this works for everyone, if you have any problems please ask ...

    
answered by 08.09.2017 / 20:01
source