从零开始学android:Android事件处理—单选钮与OnCheckedChangeListener

OnCheckedChangeListener

单选钮(RadioGroup)上也可以进行事件的处理操作,当用户选中了某选项之后也将触发相应的监听器进行若干处理,而注册事件的方法为:
public void setOnCheckedChangeListener (RadioGroup.OnCheckedChangeListener listener)。

布局文件:



    
    
        
        
    

程序文件:

package com.richard.onclickedchangelistener;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private TextView show = null;
	private RadioGroup sex = null;
	private RadioButton male = null;
	private RadioButton female = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.show = (TextView) super.findViewById(R.id.show);
		this.sex = (RadioGroup) super.findViewById(R.id.sex);
		this.male = (RadioButton) super.findViewById(R.id.male);
		this.female = (RadioButton) super.findViewById(R.id.female);
		
		this.sex.setOnCheckedChangeListener(new OnCheckedChangeListenerImpl());
	}
	
	private class OnCheckedChangeListenerImpl implements OnCheckedChangeListener{

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			String temp = null;
			if(MainActivity.this.male.getId() == checkedId){
				temp = MainActivity.this.male.getText().toString();	//取得单选文本
			}
			if(MainActivity.this.female.getId() == checkedId){
				temp = MainActivity.this.female.getText().toString();	//取得单选文本
			}
			
			MainActivity.this.show.setText("您的性别是:"+temp);		//设置文本信息
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

 测试效果:

从零开始学android:Android事件处理—单选钮与OnCheckedChangeListener_第1张图片

你可能感兴趣的:(Android)