一步一步学android之事件篇——单选按钮监听事件

时间:2022-03-09 14:46:16

在平常使用软件的时候,我们经常会碰见一些选择题,例如选择性别的时候,在男和女之间选,前面说过这个情况要用RadioGroup组件,那么点击了之后我们该怎么获取到选择的那个值呢,这就是今天要说的OnCheckedChangeListener方法。这个方法定义如下:

public static interface RadioGroup.OnCheckedChangeListener{
public void onCheckedChanged(RadioGroup group, int checkedId){ }
}

下面写个例子来看看如何监听单选按钮,效果如下:

点击前:

一步一步学android之事件篇——单选按钮监听事件

点击后:

一步一步学android之事件篇——单选按钮监听事件

下面给出程序源文件:

main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="请选择您的性别...."/>
<RadioGroup
android:id="@+id/sex"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/male">
<RadioButton
android:id="@+id/male"
android:text="男"/>
<RadioButton
android:id="@+id/female"
android:text="女"/>
</RadioGroup>
<TextView
android:id="@+id/showSex"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您的性别是:"/>
</LinearLayout>

MainActivity.java:

package com.example.oncheckedchangedlistenerdemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView; public class MainActivity extends Activity {
private TextView showSex = null;
private RadioGroup sex = null;
private RadioButton male = null;
private RadioButton female = null;
private String head = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView(){
//初始化组件
showSex = (TextView)super.findViewById(R.id.showSex);
sex = (RadioGroup)super.findViewById(R.id.sex);
male = (RadioButton)super.findViewById(R.id.male);
female = (RadioButton)super.findViewById(R.id.female);
//获取显示前缀(即您的性别是:),以便显示美观
head = showSex.getText().toString();
//未调用监听时显示默认选择内容
if(male.getId() == sex.getCheckedRadioButtonId()){
showSex.setText(head+male.getText().toString());
}else if(female.getId() == sex.getCheckedRadioButtonId()){
showSex.setText(head+female.getText().toString());
}
//为RadioGroup设置监听事件
sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
String sexTmp = "";
if(checkedId == male.getId()){
sexTmp = male.getText().toString();
}else if(checkedId == female.getId()){
sexTmp = female.getText().toString();
}
showSex.setText(head+sexTmp);
}
});
}
}

今天就到这里了。