0

I'm trying to show a radiogroup with 2 buttons in an alert dialog.

I' dynamically creating the dialog & alert on a listitem click.

It's working fine apart from the radio button IDs are incrementing each time the alert is shown (if I hit cancel then reclick a list item).

As an aside, is there a 'better' way to refer to the radio group than creating a temporary final variable?

// List item clicked
@Override
public void onItemClick(AdapterView<?> oAdapterView, View oView, int iPos, long lArg)
{
    ListView oListView = (ListView) findViewById(R.id.usage_room_list_lv);
    String strClickedItem = (String) oListView.getItemAtPosition(iPos);


    AlertDialog.Builder oAlert = new AlertDialog.Builder(this);

    oAlert.setTitle("Alert Title");
    oAlert.setMessage("Alert Message");
    oAlert.setNegativeButton(getResources().getString(R.string.cancel).toString(), null);

    RadioGroup oGroup = new RadioGroup(this);

    RadioButton oFirstButton = new RadioButton(this);
    oFirstButton.setText("First Button");

    RadioButton oSecondButton = new RadioButton(this);
    oSecondButton .setText("Second Button");

    oGroup.addView(oSecondButton);
    oGroup.addView(oAccessibleChoice);

    // Required for inside setPositiveButton below, is there a better way?
    final RadioGroup oTmpGroup = oGroup;
    oAlert.setView(oTmpGroup);

    oAlert.setPositiveButton("Done", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which)
        {
                            // This auto increments
            if (DEBUG) System.out.println(CLASS_NAME + " Clicked option: " + oTmpGroup.getCheckedRadioButtonId());
        }
    });

    oAlert.show();
}

1 Answers1

0

ID of any most View implementations will auto-increment because it is specified in constructor. To overcome this problem you could redefine id of any View subclass using setId(int) method.

Don't know anything about "better". What you want - better readability, shorter code or faster execution time? Your solution already fine, accessing reference stored in variable fast and don't clutter properties list. Though, i don't understand why you create new final variable if you don't change value of original during its scope.

weaknespase
  • 1,014
  • 8
  • 15
  • In order to refer to the group on this line `if (DEBUG) System.out.println(CLASS_NAME + " Clicked option: " + oTmpGroup.getCheckedRadioButtonId());`, the `oTmpGroup` has to be marked as final. – user3398063 Mar 09 '14 at 09:52
  • You could remove `oTmpGroup` and make final `oGroup`, since you don't change its value during execution of `onItemClicked` where you define it originally. – weaknespase Mar 09 '14 at 09:54