Как добавить динамический переключатель в соответствии с заданным количеством отсчетов?

Я пробовал этот код. При запуске эмулятора будет отображаться три переключателя в одной строке. Но для этого мне нужна кнопка. то есть; если я нажму кнопку, он должен запросить количество переключателей. тогда, если я даю счет, он должен отображать радиокнопки на основе указанного количества. Например, если я даю счету как 3, он должен отображать три переключателя в одной строке. Ваша помощь высоко ценится. Спасибо заранее.

  public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        for(int row=0; row < 1; row++)
        {
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            for(int i = 1; i < 4; i++) {
                RadioButton rdbtn = new RadioButton(this);
                rdbtn.setId((row * 2) + i);
                rdbtn.setText("Radio " + rdbtn.getId());
                ll.addView(rdbtn);
            }
            ((ViewGroup)findViewById(R.id.radiogroup)).addView(ll);
        }
    }
    }

это xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity" >

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

    </RelativeLayout>

Ответы

Ответ 1

Пожалуйста, найдите ниже код, я создал "EditText" и 'Button' в макете xml. Введите номер в "EditText" и нажмите кнопку "Тот же номер". переключателей будут добавлены в макет.

Это ваш ActivityMain

public class ActivityMain extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        final EditText editText=(EditText)findViewById(R.id.et_no);

        findViewById(R.id.btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub


                int number=Integer.parseInt(editText.getText().toString());
                addRadioButtons(number);
            }
        });

    }

    public void addRadioButtons(int number) {

    for (int row = 0; row < 1; row++) {
        RadioGroup ll = new RadioGroup(this);
        ll.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());
            ll.addView(rdbtn);
        }
        ((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
    }

  }

}

и вот ваш файл макета

<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" />



<LinearLayout
    android:layout_marginTop="20dp"
    android:layout_marginLeft="20dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <EditText android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:hint="Enter no."
        android:inputType="number"
        android:id="@+id/et_no"/>


    <Button

        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Add Radio btn"
        android:id="@+id/btn"/>
</LinearLayout>

Ответ 2

Попробуйте что-то вроде ниже:

RadioGroup rgp= (RadioGroup) findViewById(R.id.radiogroup);
RadioGroup.LayoutParams rprms;

for(int i=0;i<3;i++){
      RadioButton radioButton = new RadioButton(this);
      radioButton.setText("new"+i);
      radioButton.setId("rbtn"+i);
      rprms= new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      rgp.addView(radioButton, rprms);
}

Ответ 3

Это способ сделать это:

    RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);        
    int buttons = 5;
    for (int i = 1; i <= buttons ; i++) {
        RadioButton rbn = new RadioButton(this);
        rbn.setId(i + 1000);
        rbn.setText("RadioButton" + i);
        rgp.addView(rbn);
    }

введите описание изображения здесь

Но что, если вам нужно сделать это по горизонтали, просто добавьте ориентацию (значение по умолчанию - вертикально) с помощью метода setOrientation():

    RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
    rgp.setOrientation(LinearLayout.HORIZONTAL);
    int buttons = 5;
    for (int i = 1; i <= buttons; i++) {
        RadioButton rbn = new RadioButton(this);
        rbn.setId(1 + 1000);
        rbn.setText("RadioButton" + i);
        rbn.setLayoutParams(params);
        rgp.addView(rbn);
    }

введите описание изображения здесь


Это полный код:

прежде всего определяя внутри нашего макета RadioGroup:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</RelativeLayout>

Код в MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Defining 5 buttons.
        int buttons = 5;
        AppCompatRadioButton[] rb = new AppCompatRadioButton[buttons];

        RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
        rgp.setOrientation(LinearLayout.HORIZONTAL);

        for (int i = 1; i <= buttons; i++) {
            RadioButton rbn = new RadioButton(this);
            rbn.setId(i + 1000);
            rbn.setText("RadioButton" + i);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
            rbn.setLayoutParams(params);
            rgp.addView(rbn);
        }

    }
}

Ответ 4

Добавьте a Button и EditText в xml и введите input from editText в переменную inputValue и попробуйте это,

 public class MyActivity extends Activity {

    /**
     * Called when the activity is first created.
     */
     LinearLayout ll=null;
     ViewGroup  vwgroup;
     Button btnClick;   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    vwgroup=((ViewGroup)findViewById(R.id.radiogroup)
    btnClick=(Button)findViewById(R.id.button1);


        btnClick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(ll!=null)
                    viewgroup.removeView(ll);
                ll = new LinearLayout(this);
                for(int i = 1; i < inputValue; i++) {
                    RadioButton rdbtn = new RadioButton(this);
                    rdbtn.setId((row * 2) + i);
                    rdbtn.setText("Radio " + rdbtn.getId());
                    ll.addView(rdbtn);
                }
                vwgroup.addView(ll);

            }
        });
    }
    }