这可能是一个非常简单的问题,但我是Android的初学者,请帮助它。
我在没有RadioButton
的XML中创建了两个RadioGroup
,并且在MainActivity.java
中创建了一个RadioGroup
,如何在RadioButton
中添加RadioGroup
{1}}?代码如下......
activity_main.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="com.avisingh.radiobuttontest.MainActivity">
<RadioButton
android:id="@+id/male_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Male"/>
<RadioButton
android:id="@+id/female_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Female"/>
</RelativeLayout>
MainActivity.java
package com.avisingh.radiobuttontest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RadioButton maleBtn = (RadioButton)findViewById(R.id.male_button);
final RadioButton femaleBtn = (RadioButton)findViewById(R.id.female_button);
RadioGroup radioGroup = new RadioGroup(this);
//radioGroup.add(maleBtn); // its getting error
//radioGroup.add(femaleBtn); // its getting error
//radioGroup.addView(maleBtn); // it is also getting error
//radioGroup.addView(femaleBtn); // it is also getting error
}
}
有没有任何方法可以添加RadioButton
之类的java?
答案 0 :(得分:1)
您可以在'activity_main.xml'
中添加'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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.avisingh.radiobuttontest.MainActivity">
<RadioGroup
android:id="@+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/male_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Male"/>
<RadioButton
android:id="@+id/female_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Female"/>
</RadioGroup>
答案 1 :(得分:1)
以下是如何做到这一点
RadioButton radioButton = new RadioButton(this);
radioButton.setText("Test Radio");
radioButton.setId(1);
radioGrp.addView(radioButton);
如果太多尝试将其置于循环中
for (int i = 0; i < radioItems.length; i++) {
RadioButton radioButton = new RadioButton(this);
radioButton.setText(radioItems[i]);
radioButton.setId(i);
radioGrp.addView(radioButton);
}