Crear un cuadro de diálogo personalizado con lista de botones de radio

Tengo un método en el que tengo una lista de valores:

/** * ISO * */ public void getISO(View view) { // Open dialog with radio buttons List<String> supported_isos = preview.getSupportedISOs(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); String current_iso = sharedPreferences.getString(MainActivity.getISOPreferenceKey(), "auto"); } 

Este método es enjected on onClick () de un ImageButton :

 android:onClick="getISO" 

Pero necesito rapresent esta lista en un diálogo con los botones de radio. Es posible que los valores de preferencia ya estén seleccionados en el diálogo .. ¿Es posible?

Llame a showRadioButtonDialog() desde el botón.

Este es sólo un ejemplo:

 private void showRadioButtonDialog() { // custom dialog final Dialog dialog = new Dialog(mActivity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.radiobutton_dialog); List<String> stringList=new ArrayList<>(); // here is list for(int i=0;i<5;i++) { stringList.add("RadioButton " + (i + 1)); } RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radio_group); for(int i=0;i<stringList.size();i++){ RadioButton rb=new RadioButton(mActivity); // dynamically creating RadioButton and adding to RadioGroup. rb.setText(stringList.get(i)); rg.addView(rb); } dialog.show(); } 

Su vista de diseño: radiobutton_dialog.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RadioGroup android:id="@+id/radio_group" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:orientation="vertical"> </RadioGroup> </LinearLayout> 

Introduzca aquí la descripción de la imagen

Nota: puede personalizar su vista de diálogo (como la configuración de título, mensaje, etc.)

Editar: Para recuperar el valor del RadioButton seleccionado, debes implementar setOnCheckedChangeListener para tu RadioGroup como:

  rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { int childCount = group.getChildCount(); for (int x = 0; x < childCount; x++) { RadioButton btn = (RadioButton) group.getChildAt(x); if (btn.getId() == checkedId) { Log.e("selected RadioButton->",btn.getText().toString()); } } } }); 

Mejor manera y fácil

 void dialog(){ AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); //alt_bld.setIcon(R.drawable.icon); alt_bld.setTitle("Select a Group Name"); alt_bld.setSingleChoiceItems(grpname, -1, new DialogInterface .OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), "Group Name = "+grpname[item], Toast.LENGTH_SHORT).show(); dialog.dismiss();// dismiss the alertbox after chose option } }); AlertDialog alert = alt_bld.create(); alert.show(); ///// grpname is a array where data is stored... } 

Una manera limpia es como esto:

http://developer.android.com/guide/topics/ui/dialogs.html

Extracto de (Adición de una lista de opción múltiple persistente o de una sola opción)

 mSelectedItems = new ArrayList(); // Where we track the selected items AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Set the dialog title builder.setTitle(R.string.pick_toppings) // Specify the list array, the items to be selected by default (null for none), // and the listener through which to receive callbacks when items are selected .setMultiChoiceItems(R.array.toppings, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { // If the user checked the item, add it to the selected items mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } }) // Set the action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // User clicked OK, so save the mSelectedItems results somewhere // or return them to the component that opened the dialog ... } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { ... } }); return builder.create(); 

Lea acerca de http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setSingleChoiceItems(int, int, android.content.DialogInterface.OnClickListener)

Ninguna vista personalizada es necesaria.

Cuando desee mostrar datos de la base de datos SQLIte

 private void showRadioButtonDialog() { // custom dialog final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.radiobutton_dialog); List<String> stringList=new ArrayList<>(); // here is list if (cursor.moveToFirst()) { do { String a=( cursor.getString(0).toString()); String b=(cursor.getString(1).toString()); String c=(cursor.getString(2).toString()); String d=(cursor.getString(3).toString()); stringList.add(d); } while (cursor.moveToNext()); } RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.radio_group); for(int i=0;i<stringList.size();i++) { RadioButton rb=new RadioButton(this); // dynamically creating RadioButton and adding to RadioGroup. rb.setText(stringList.get(i)); rg.addView(rb); } dialog.show(); rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { int childCount = group.getChildCount(); for (int x = 0; x < childCount; x++) { RadioButton btn = (RadioButton) group.getChildAt(x); if (btn.getId() == checkedId) { Toast.makeText(getApplicationContext(), btn.getText().toString(), Toast.LENGTH_SHORT).show(); } } } }); } 

Mira esto. Esta es la fila personalizada dialog_row.xml que debe usar en CustomAdapter:

  <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RadioButton android:id="@+id/list" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> 

A continuación, en el método onclick:

 @Override public void onClick(View arg0) { // custom dialog final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.custom_layout); //Your custom layout dialog.setTitle("Title..."); Listview listview= (ListView) dialog.findViewById(R.id.listview); CustomAdapter adapter=new CustomAdapter(context,your_list); listview.setadapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Do something } }); dialog.show(); } 

Enlace para el tutorial

  • El mejor enfoque para cargar múltiples bibliotecas nativas en la aplicación para Android
  • La restricción UNIQUE falló: base de datos sqlite: android
  • Enum de tamaño de byte en Java
  • NoClassDefFoundError en Runtime en clase dentro de .AAR en Android Studio
  • Android Dx advertencia: Ignorar el atributo InnerClasses para un problema de archivo interno anónimo jar
  • ¿Cualquier manera de agarrar un icono de la insignia del URL del Web site, programmatically?
  • Android - Mientras maneja una imagen es mejor almacenarla o usarla en memoria temporal?
  • Intentar invocar el método virtual. Aplicación para mostrar la ubicación
  • Vista de la imagen de la escala de submuestreo - haga clic en los marcadores de pin en Imageview
  • ¿Cómo encontrar el almacenamiento interno (Almacenamiento predeterminado del teléfono) y el almacenamiento externo (tarjeta SD extraíble) en android?
  • Android: ClassNotFoundException al pasar el objeto serializable a la actividad
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.