
android开发之获取RadioGroup选中项的值
发布日期:2021-05-10 03:33:06
浏览次数:13
分类:精选文章
本文共 1425 字,大约阅读时间需要 4 分钟。
一、布局代码
以下是一个布局代码示例,用于定义一个包含两个RadioButton的RadioGroup。布局代码中,我们采用了嵌套的.addView方法来添加RadioButton控件。为了实现水平排列,RadioGroup的属性设置为orientation="horizontal"。与此同时,通过设置layout_marginRight属性,我们可以将第二个RadioButton在布局中右侧留出一定的间隙。
二、Java代码
以下是与上述布局代码对应的Java代码实现。在Activity中,我们首先通过findViewById方法获取RadioGroup控件。然后,通过设置OnCheckedChangeListener事件监听器,来获取用户选择的RadioButton信息。最后,通过getCheckedRadioButtonId()方法确定所选RadioButton的id,并使用findViewById方法获取到具体的RadioButton实例,从而获取到用户选择的值。
public class activity01 extends AppCompatActivity { private RadioButton radiobutton; private RadioGroup rdgroup; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity01); // 获取RadioGroup控件 rdgroup = (RadioGroup) findViewById(R.id.rdgroup); // 设置RadioGroup选中项改变的监听器 rdgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) { // 通过getCheckedRadioButtonId()获取被选中的RadioButton的id radiobutton = (RadioButton) findViewById(i); // 获取RadioButton的文本值 String sex = radiobutton.getText().toString(); } }); } }
通过上述布局代码和Java代码,我们实现了一个简单的性别选择界面。用户可以通过点击RadioButton进行性别选择,并在代码中获取最终的选项值。