Muaaz Kasker Muaaz Kasker - 4 years ago 104
Android Question

Android - How to use spinner int value to programatically add views

here is my code

mspin=(Spinner) findViewById(R.id.spinner);
Integer[] items = new Integer[]{1,2,3,4,5,6,7,8,9,10};
ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);

RG = (RadioGroup) findViewById(R.id.radioGroup);

mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

int TYPE = Integer.parseInt(mspin.getSelectedItem().toString());

setRadios(TYPE);

}

public void onNothingSelected(AdapterView<?> parent) {

}
});

}

public void setRadios(int mk) {

for(int i=0; i==mk; i++){

RadioButton bg = new RadioButton(this);
bg.setText("hello, this is mk");

RG.addView(bg);

}

}


I am trying to get an int value from a spinner and then add that many RadioButtons to the RadioGruop RG. however, when I run the code it does nothing when I click on a spinner value.
any help is appreciated and thanked in advance

Answer Source

try this method:

public void setRadios(int number) {

    for (int row = 0; row < 1; row++) { //add to first row
        RadioGroup rg = new RadioGroup(this);
        rg.setOrientation(LinearLayout.HORIZONTAL);

        for (int i = 1; i <= number; i++) {
            RadioButton rdbtn = new RadioButton(this);
            rdbtn.setId((row * 2) + i);
            rdbtn.setText("Radio " + rdbtn.getId());
            rg.addView(rdbtn);
        }
        ((ViewGroup) findViewById(R.id.radiogroup)).addView(rg);
    }

  }

in XML:

<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical" />

you are not adding radiobutton to the viewgroup

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download