Android學習之RadioGroup和RadioButton


轉載自:http://my.oschina.net/amigos/blog/59261

 

實現RadioButton由兩部分組成,也就是RadioButtonRadioGroup配合使用.RadioGroup是單選組合框,可以容納多個RadioButton的容器.在沒有RadioGroup的情況下,RadioButton可以全部都選中;當多個RadioButtonRadioGroup包含的情況下,RadioButton只可以選擇一個。並用setOnCheckedChangeListener來對單選按鈕進行監聽

01 RadioGroup相關屬性:
02  
03 RadioGroup.getCheckedRadioButtonId ();--獲取選中按鈕的id
04  
05 RadioGroup.clearCheck ();//---清除選中狀態
06  
07 RadioGroup.check (int id);//---通過參入選項id來設置該選項為選中狀態如果傳遞-1作為指定的選擇標識符來清除單選按鈕組的勾選狀態,相當於調用clearCheck()操作
08  
09 setOnCheckedChangeListener (RadioGroup.OnCheckedChangeListener listener); //--一個當該單選按鈕組中的單選按鈕勾選狀態發生改變時所要調用的回調函數
10  
11 addView (View child, int index, ViewGroup.LayoutParams params);//---使用指定的布局參數添加一個子視圖
12  
13 //參數  child 所要添加的子視圖    index 將要添加子視圖的位置  params 所要添加的子視圖的布局參數
14  
15 RadioButton.getText();//獲取單選框的值
16  
17 //此外,RadioButton的checked屬性設置為true,代碼里調用RadioButton的check(id)方法,不會觸發onCheckedChanged事件

RadioButton和RadioGroup的關系:

1、RadioButton表示單個圓形單選框,而RadioGroup是可以容納多個RadioButton的容器

2、每個RadioGroup中的RadioButton同時只能有一個被選中

3、不同的RadioGroup中的RadioButton互不相干,即如果組A中有一個選中了,組B中依然可以有一個被選中

4、大部分場合下,一個RadioGroup中至少有2個RadioButton

5、大部分場合下,一個RadioGroup中的RadioButton默認會有一個被選中,並建議您將它放在RadioGroup中的起始位置

看案例:

1.定義布局文件:

01 <?xml version="1.0" encoding="utf-8"?>
02 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="match_parent"
04     android:layout_height="match_parent" >
05  <LinearLayout
06         android:orientation="vertical"
07         android:layout_width="match_parent"
08         android:layout_height="wrap_content"
09         android:layout_marginRight="5dp" >
10            
11            <TextView
12         android:id="@+id/radiogroup_info_id"
13         android:layout_width="228px"
14         android:layout_height="wrap_content"
15         android:text="我選擇的是...?"
16         android:textSize="30sp"   
17          />  
18             
19           <RadioGroup
20             android:id="@+id/radioGroup_sex_id"
21             android:layout_width="match_parent"
22             android:layout_height="match_parent"
23               >
24               <RadioButton
25                 android:id="@+id/boy_id"
26                 android:layout_width="match_parent"
27                 android:layout_height="match_parent"  
28                 android:text="Boy"
29                   />
30               <RadioButton
31                 android:id="@+id/girl_id"
32                 android:layout_width="match_parent"
33                 android:layout_height="match_parent"  
34                 android:text="Girl"
35                   />
36                
37           </RadioGroup>
38           <Button
39                android:id="@+id/radio_clear"
40                android:layout_width="match_parent"
41                android:layout_height="match_parent"  
42                android:text="清除選中按鈕"
43               />
44            
45           <Button
46                android:id="@+id/radio_add_child"
47                android:layout_width="match_parent"
48                android:layout_height="match_parent"  
49                android:text="添加單選項"
50               />
51            
52        </LinearLayout>
53  </ScrollView>

2.java代碼文件

01 package com.dream.app.start.first.radiobutton;
02  
03 import com.dream.app.start.R;
04 import com.dream.app.start.R.id;
05 import com.dream.app.start.R.layout;
06 import com.dream.app.start.three.utils.PublicClass;
07  
08 import android.app.Activity;
09 import android.os.Bundle;
10 import android.view.View;
11 import android.view.View.OnClickListener;
12 import android.view.ViewGroup.LayoutParams;
13 import android.widget.Button;
14 import android.widget.RadioButton;
15 import android.widget.RadioGroup;
16 import android.widget.RadioGroup.OnCheckedChangeListener;
17 import android.widget.TextView;
18 import android.widget.ToggleButton;
19  
20 public class RadioButtonDemo extends PublicClass {
21     private  TextView   textView=null;
22     private  RadioGroup  radioGroup=null;
23     private  RadioButton  radioButton_boy,radioButton_girl;
24     private Button   radio_clear,child;
25     /* (non-Javadoc)
26      * <a href="http://my.oschina.net/u/244147" target="_blank" rel="nofollow">@see</a>  android.app.Activity#onCreate(android.os.Bundle)
27      */
28     @Override
29     protected void onCreate(Bundle savedInstanceState) {
30         // TODO Auto-generated method stub
31         super.onCreate(savedInstanceState);
32          
33         setContentView(R.layout.layout_frist_radiobuton);
34          
35         textView = (TextView)findViewById(R.id.radiogroup_info_id); 
36          
37         //radioGroup
38         radioGroup=(RadioGroup)findViewById(R.id.radioGroup_sex_id);
39         radioButton_boy=(RadioButton)findViewById(R.id.boy_id);
40         radioButton_girl=(RadioButton)findViewById(R.id.girl_id);
41         child=(Button)findViewById(R.id.radio_add_child);
42         //---
43         radioGroup.setOnCheckedChangeListener(listen);
44         radio_clear=(Button)findViewById(R.id.radio_clear);
45         radio_clear.setOnClickListener(onClick);
46         child.setOnClickListener(onClick);
47     }
48      
49     private OnCheckedChangeListener  listen=new OnCheckedChangeListener() {
50          
51         @Override
52         public void onCheckedChanged(RadioGroup group, int checkedId) {
53         int id= group.getCheckedRadioButtonId();
54             switch (group.getCheckedRadioButtonId()) {
55             case R.id.girl_id:
56                 textView.setText("我選擇的是:"+radioButton_girl.getText());
57                 break;
58             case R.id.boy_id:
59                 textView.setText("我選擇的是:"+radioButton_boy.getText());
60                 break;
61             default:
62                 textView.setText("我選擇的是:新增");
63                 break;
64             }
65              
66         }
67     };
68     private OnClickListener  onClick=new OnClickListener() {
69          
70         @Override
71         public void onClick(View v) {
72             radio_clear=(Button)v;
73             switch (radio_clear.getId()) {
74             case R.id.radio_clear:
75                 radioGroup.check(-1);//清除選項
76 //              radioGroup.clearCheck(); //清除選項
77                 textView.setText("我選擇的是...?");
78                 break;
79             case R.id.radio_add_child:
80                                //新增子
81                 RadioButton  newRadio =new RadioButton(getApplicationContext());
82                 newRadio.setText("新增");
83                 radioGroup.addView(newRadio, radioGroup.getChildCount());              
84                 break;
85                 //
86              
87            default:
88                 break;
89             }
90         }
91     };
92  
93 }

 運行效果:

運行效果

 

選中一個按鈕時的截圖

3.

點擊添加單選項的截圖

 4:可以通過設置如下屬性可以使單選按鈕在顯示文本的右邊

  android:button="@null"                    

  android:drawableRight="@android:drawable/btn_radio"

 效果:

RadioButton和CheckBox的區別:

1、單個RadioButton在選中后,通過點擊無法變為未選中

單個CheckBox在選中后,通過點擊可以變為未選中

2、一組RadioButton,只能同時選中一個

一組CheckBox,能同時選中多個

3、RadioButton在大部分UI框架中默認都以圓形表示

CheckBox在大部分UI框架中默認都以矩形表示

==================================================

☆定制RadioButton樣式RadioButton長成什么樣子是由其Background、Button等屬性決定的,Android系統 
使用style定義了默認的屬性,在android源碼 

android/frameworks/base/core/res/res/values/styles.xml中可以看到默認的定義:

1 <style name="Widget.CompoundButton.RadioButton"
2         <item name="android:background">@android:drawable/btn_radio_label_background</item
3         <item name="android:button">@android:drawable/btn_radio</item
4 </style>

 

即其背景圖是btn_radio_label_background,其button的樣子是btn_radio 
btn_radio_label_background是什么? 
其路徑是android/frameworks/base/core/res/res/drawable-mdpi/btn_radio_label_background.9.png 
可以看到是一個NinePatch圖片,用來做背景,可以拉伸填充。
btn_radio是什么? 

其路徑是android/frameworks/base/core/res/res/drawable/btn_radio.xml 

是個xml定義的drawable,打開看其內容:

01 <selector xmlns:android="http://schemas.android.com/apk/res/android">     
02     <item android:state_checked="true" android:state_window_focused="false" 
03           android:drawable="@drawable/btn_radio_on" /> 
04     <item android:state_checked="false" android:state_window_focused="false" 
05           android:drawable="@drawable/btn_radio_off" /> 
06    
07     <item android:state_checked="true" android:state_pressed="true" 
08           android:drawable="@drawable/btn_radio_on_pressed" /> 
09     <item android:state_checked="false" android:state_pressed="true" 
10           android:drawable="@drawable/btn_radio_off_pressed" /> 
11    
12     <item android:state_checked="true" android:state_focused="true" 
13           android:drawable="@drawable/btn_radio_on_selected" /> 
14     <item android:state_checked="false" android:state_focused="true" 
15           android:drawable="@drawable/btn_radio_off_selected" /> 
16    
17     <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" /> 
18     <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" /> 
19 </selector>

 

<item android:state_checked="true" android:state_pressed="true"  
          android:drawable="@drawable/btn_radio_on_pressed" />  

意思即為當radiobutton被選中時,並且被按下時,其Button應該長成btn_radio_on_pressed這個樣子。


文件是android/frameworks/base/core/res/res/drawable-mdpi/btn_radio_on_pressed.png 
drawable的item中可以有以下屬性: 

1 android:drawable="@[package:]drawable/drawable_resource"
2 android:state_pressed=["true" | "false"]
3 android:state_focused=["true" | "false"]
4 android:state_selected=["true" | "false"]
5 android:state_active=["true" | "false"]
6 android:state_checkable=["true" | "false"]
7 android:state_checked=["true" | "false"]
8 android:state_enabled=["true" | "false"]
9 android:state_window_focused=["true" | "false"]

 當按鈕的狀態和某個item匹配后,就會使用此item定義的drawable作為按鈕圖片。  

從上面分析我們如果要修改RadioButton的外觀,

 自定義有三種方式:

1.方式一:

 

01 <?xml version="1.0" encoding="utf-8"?>    
02 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
03 <!--  未選中->  
04     <item    
05          android:state_checked="false"    
06          android:drawable="@drawable/tabswitcher_long" /> 
07 <!--選中->    
08     <item    
09         android:state_checked="true"    
10         android:drawable="@drawable/tabswitcher_short" />    
11 </selector>

 

在布局文件中使用

 

1 <RadioGroup 
2   ... 
3
4 <RadioButton 
5   ... 
6 android:button="@null" 
7 android:background="@drawable/radio" 
8 /> 
9 </RadioGroup>

android:button="@null"  去除RadioButton前面的圓點
2.方式二:在JAVA代碼中定義

1 @Override  
2 public boolean onTouchEvent(MotionEvent event) { 
3   if(event.getActionMasked() == MotionEvent.ACTION_DOWN){ 
4     this.setBackgroundResource(com.wxg.tab.R.drawable.main_bg); 
5   }else if(event.getActionMasked()== MotionEvent.ACTION_DOWN) { 
6     this.setBackgroundResource(com.wxg.tab.R.drawable.hui); 
7   
8   return super.onTouchEvent(event); 
9 }

去除RadioButton前面的圓點adioButton.setButtonDrawable(android.R.color.transparent);

3. 方式三

使用XML文件定義,在JAVA代碼中使用 radioButton.setBackgroundResource(R.drawable.radio);調用

==============================================================

                                                設置RadioButton在文字的右邊

 

1 <b><RadioButton  
2             android:id="@+id/button2"  
3             android:layout_width="fill_parent"  
4             android:layout_height="50dip"  
5             android:button="@null"  
6             android:drawableRight="@android:drawable/btn_radio"  //在右邊
7             android:paddingLeft="30dip"  
8             android:text="Android高手"  
9             android:textSize="20dip" />   </b>

 

================================================================

 

自定義 radiobutton 文字顏色隨選中狀態而改變

 主要是寫一個 color selector

 在res/建一個文件夾取名color
 res/color/color_radiobutton.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
3  
4      <item android:state_checked="true" 
5      android:color="@color/color_text_selected"/>
6      <!--  not selected -->
7      <item android:color="@color/color_text_normal"/>
8 </selector>

 

布局文件定義控件:
01 <RadioButton
02             android:id="@+id/radiobutton_1"
03             android:layout_width="wrap_content"
04             android:layout_height="wrap_content"
05             android:background="@drawable/selector_radio"
06             android:button="@null"
07             android:checked="true"
08              android:gravity="center"
09              android:text="目錄"
10             <!--自定義文本顏色   -->
11             android:textColor="@color/color_radiobutton"
12             android:textSize="@dimen/font_size"
13             android:textStyle="bold" />

 

============================================================
RadioButton上顯示圖片和文字

使用XML文件很簡單就可以實現,但是有時必須要使用java code 的方式動態實現,這就有些復雜了,這需要繼承RadioButton並覆蓋其中的onDraw方法。

在代碼中的image是Bitmap對象。

01 @Override 
02  
03 protected void onDraw(Canvas canvas) { 
04  
05   super.onDraw(canvas); 
06  
07    if(image!=null){ 
08  
09     Paint pt = new Paint(); 
10  
11     pt.setARGB(255,66,66,66); 
12  
13     //消除鋸齒 
14  
15     pt.setAntiAlias(true); 
16  
17     //居中顯示圖片 
18  
19     int imageX=(int)(this.getWidth()-image.getWidth())/2
20  
21     canvas.drawBitmap(image,imageX,5,pt); 
22  
23     pt.setARGB(255,255,255,255); 
24  
25     //居中顯示字符串 
26  
27     int strX=(int)(this.getWidth()-name.getBytes().length*5.5)/2
28  
29     canvas.drawText(name,strX,(image.getHeight()+15),pt); 
30     }
31  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM