在我们平时在注册个人信息的时候,经常会让我们选择是男生还是女生,那么这个单选框在Android中是怎么实现的呢?现在我们就来学习一下吧
首先我们要明白实现这样一个效果需要哪几部?
1、在layout布局文件中建立一个文件,我起的名字为activity_radio.xml
代码为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical" >
<!--
RadioButton 要想实现多选一的效果必须放到RadioGroup 中,否则无法实现多选一的效果.
技巧:要面向RadioGroup 编程,不要面向RaidoButton 编程,否则将增加很大代码量
android:orientation="vertical":执行按钮组的方向,默认值是vertical.
RadioGroup的父类时LinearLayout,但方向的默认值不再是线性布局的水平方向了,而是改成了垂直方向.
-->
< RadioGroup
android:id = "@+id/radioGroup_gender"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:orientation = "vertical"
>
< RadioButton
android:id = "@+id/radioButton_male"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center_horizontal"
android:checked = "true"
android:text = "男" />
< RadioButton
android:id = "@+id/radioButton_female"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center_horizontal"
android:checked = "false"
android:text = "女" />
</ RadioGroup >
</ LinearLayout >
|
2、在MainActivity中实现细节的功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
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 );
}
/**
* 当单选按钮的状态发生变化时自动调用的方法
* @param group 单选按钮所在的按钮组的对象
* @param checkedId 用户选中的单选按钮的id值
*/
@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+ ")==" );
}
}
|
那么以上就是一个简单的单选框的实现,希望对大家会有所帮助。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/h_Snow_1/article/details/80336701