Android 控件开发之 RadioButton

单选按钮RadioButton在Android平台上也应用的非常多,比如一些选择项的时候,会用到单选按钮,实现单选按钮由两部分组成,也就是RadioButton和RadioGroup配合使用

RadioButton的单选按钮;

RadioGroup是单选组合框,用于将RadioButton框起来;

在没有RadioGroup的情况下,RadioButton可以全部都选中;

当多个RadioButton被RadioGroup包含的情况下,RadioButton只可以选择一个;

注意:单选按钮的事件监听用setOnCheckedChangeListener来对单选按钮进行监听


 RadioButton效果:

  

  

   本程序的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"
    >
<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:orientation="vertical">
    
<RadioButton
    android:id="@+id/radioBlue"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="blue"/>
    
<RadioButton
    android:id="@+id/radioRed"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="red"/> 
    
</RadioGroup>

</LinearLayout>



RadioButton事件响应setOnCheckedChangeListener

本程序的java源码:

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.Toast;


public class RadioButtonActivity extends Activity 
{
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
              
         final RadioGroup group = (RadioGroup)findViewById(R.id.radioGroup);   

         group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
         {        
            @Override  
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {     
		switch(checkedId)
		{
		case R.id.radioBlue:
			Toast.makeText(getApplicationContext(), "你选中了蓝色按钮", Toast.LENGTH_LONG).show();
			break;
		case R.id.radioRed:
			Toast.makeText(getApplicationContext(), "你选中了红色按钮", Toast.LENGTH_LONG).show();  
			break;
		}
            }   
        });   
    }   
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值