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


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章