從頭學Android之RadioButton和CheckBox

來源:互聯網
上載者:User

RadioButton
 
類結構圖:


 
RadioButton很好理解就是我們做Web開發裡的選項按鈕,需要注意的是我們在做Web開發需要將選項按鈕的名字設定成一樣,在這裡Android開發,我們需要將兩個或者更多的RadioButton放在一個RadioGroup裡
 
實戰演練:
1、如何設定RadioButton的對齊:
通過android:orientation其值有:vertical、horizontal
垂直:

<RadioGroup android:id="@+id/raGroup01" 
 
      android:layout_width="fill_parent" android:layout_height="wrap_content" 
 
      android:orientation="vertical"> 
 
      <RadioButton android:id="@+id/raBtn01" android:text="男" /> 
 
      <RadioButton android:id="@+id/raBtn02" android:text="女" /> 
 
   </RadioGroup> 

效果:

水平:

<RadioGroup android:id="@+id/raGroup02" 
 
      android:layout_width="fill_parent" android:layout_height="wrap_content" 
 
      android:orientation="horizontal"> 
 
      <RadioButton android:id="@+id/rautf" android:text="UTF" /> 
 
      <RadioButton android:id="@+id/ragbk" android:text="GBK" /> 
 
   </RadioGroup> 

效果:

2、如何讓RadioButton設定成選中
android:checkedButton="@+id/rautf"

<RadioGroup android:id="@+id/raGroup02" 
 
      android:layout_width="fill_parent" android:layout_height="wrap_content" 
 
      android:orientation="horizontal" 
 
      android:checkedButton="@+id/rautf"> 
 
      <RadioButton android:id="@+id/rautf" android:text="UTF" /> 
 
      <RadioButton android:id="@+id/ragbk" android:text="GBK" /> 
 
   </RadioGroup> 

 
效果:
 
添加監聽器:

radioButton01 = (RadioButton) findViewById(R.id.raBtn01); 
 
  
 
      radioButton01.setOnClickListener(new OnClickListener() { 
 
        public void onClick(View v) { 
 
           String text = radioButton01.getText().toString(); 
 
           System.out.println(text); 
 
  
 
        } 
 
      }); 
 
  

 
 
CheckBox
 
類結構圖:

 
執行個體:

<TextView android:layout_width="fill_parent" 
 
      android:layout_height="wrap_content" android:text="愛好" /> 
 
  
 
   <CheckBox android:id="@+id/chckBox01" android:text="體育" 
 
      android:layout_width="wrap_content" android:layout_height="wrap_content" /> 
 
  
 
   <CheckBox android:id="@+id/chckBox02" android:text="文學" 
 
      android:layout_width="wrap_content" android:layout_height="wrap_content" 
 
      android:checked="true" /> 
 
  

效果:
 
為CheckBox添加監聽器註冊事件

checkBox01.setOnClickListener(new OnClickListener() { 
 
 
 
     @Override 
 
     public void onClick(View v) { 
 
        System.out.println(checkBox01.getText().toString()); 
 
 
 
     } 
 
   }); 

摘自:jiahui524專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.