End.Game End.Game - 6 months ago 48
Android Question

Create a custom dialog with radio buttons list

I've got a method in which i have a list of values:

/**
* 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");

}


This method is enjected on onClick() of a
ImageButton
:

android:onClick="getISO"


But i need to rapresent this list in a dialog with radio buttons. Possibly the preference values should be already selected in the dialog.. Is it possible?

Answer

This is just an example:

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

    }

your layout view: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>

enter image description here

Note: you can customize your dialog view (like setting title, message etc.)

Edit: To retrieving value of the selected RadioButton you have to implement setOnCheckedChangeListener listener for your RadioGroup as :

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

                    }
                 }
            }
        });