单选按钮RadioGroup与RadioButton实例

 

RadioGroupRadioButton实例

*********

java文件

*********

package com.pms.myradiobutton;

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

public class MyRadioButton extends Activity {
	/*声明各个控件的引用*/
	private RadioGroup  rg;
	private RadioButton rb1;
	private TextView    tv;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        /*得到各个控件的引用*/
        rg = (RadioGroup) findViewById(R.id.rg);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        tv = (TextView) findViewById(R.id.tv);
        
        /*为RadioGroup添加监听事件*/
        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {       	
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if(checkedId == rb1.getId())
				{
					tv.setText("回答正确!");
				}
				else
				{
					tv.setText("回答错误,赶紧把书翻回去重学!");
				}
			}
		});
        
    }
}


布局文件

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
	android:id="@+id/tv"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="android属于哪家公司?"
    />
   <!-- 添加一个RadioGroup控件,垂直摆放 -->
<RadioGroup
	android:id="@+id/rg"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"	
	>
	<RadioButton
		android:id="@+id/rb1"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="google"
		/>
	<RadioButton
		android:id="@+id/rb2"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="apple"
		/>
	<RadioButton
		android:id="@+id/rb3"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="microsoft"
		/>
</RadioGroup>		
</LinearLayout>


 

运行结果:

总结:

单选按钮注册监听器的方法:

rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

}
});

判断是否选中方法getId()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值