在我们平时在注册个人信息的时候,经常会让我们选择是男生还是女生,那么这个单选框在Android中是怎么实现的呢?现在我们就来学习一下吧
首先我们要明白实现这样一个效果需要哪几部?
1、在layout布局文件中建立一个文件,我起的名字为activity_radio.xml
代码为:
2、在MainActivity中实现细节的功能
package com.hsj.example.commoncontroldemo02;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity_bak06 extends AppCompatActivity implements RadioGroup.onCheckedChangeListener {
private RadioGroup radioGroup_gender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
this.radioGroup_gender= (RadioGroup) this.findViewById(R.id.radioGroup_gender);
this.radioGroup_gender.setonCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//得到用户选中的 RadioButton 对象
RadioButton radioButton_checked= (RadioButton) group.findViewById(checkedId);
String gender=radioButton_checked.getText().toString();
Toast.makeText(this,gender,Toast.LENGTH_LONG).show();
switch (checkedId){
case R.id.radioButton_male:
//当用户点击男性按钮时执行的代码
System.out.println("===男性===");
break;
case R.id.radioButton_female:
//当用户点击女性按钮时执行的代码
System.out.println("===女性===");
break;
}
System.out.println("===onCheckedChanged(RadioGroup group="+group+", int checkedId="+checkedId+")==");
}
}
那么以上就是一个简单的单选框的实现,希望对大家会有所帮助。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



