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

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

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

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

点击前:

一步一步学android之事件篇——单选按钮监听事件_第1张图片



点击后:

一步一步学android之事件篇——单选按钮监听事件_第2张图片


下面给出程序源文件:

main.xml:


    
	
	    
	    
	
	

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);
			}
		});
	}
}


今天就到这里了。



你可能感兴趣的:(一步一步学Android)