Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 RadioGroup 與 RadioButton 實作單選與預設選中

編輯:關於 Android 程式設計

本文將透過 RadioGroup 搭配 RadioButton 來實作「組內單選」。所謂 RadioGroup,就是把多個 RadioButton 進行分組,讓它們能被統一管理與控制,確保同一時間只有一個選項被選中。此外,我們還會示範如何設定預設選中項,並即時取得選中的值。

效果圖如下:


具體實作

1. activity_main.xml

      

2. strings.xml

  RadioGroupDemo 請選擇你的性別: Settings 男 女  

3. MainActivity.java

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); defaultStr = this.getResources().getString(R.string.please_selected); seletedTv = (TextView) this.findViewById(R.id.diplay_seleted_item_tv); sexRg = (RadioGroup) this.findViewById(R.id.sex_rg); manRb = (RadioButton) this.findViewById(R.id.man_rb); womanRb = (RadioButton) this.findViewById(R.id.woman_rb); manRb.setChecked(true); seletedTv.setText(defaultStr + manRb.getText().toString()); sexRg.setOnCheckedChangeListener(new OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup rg, int checkedId) { // TODO Auto-generated method stub if(checkedId == manRb.getId()){ seletedTv.setText(defaultStr + manRb.getText().toString()); }else if(checkedId == womanRb.getId()){ seletedTv.setText(defaultStr + womanRb.getText().toString()); }else{ seletedTv.setText(defaultStr); } } }); }

重點在於:透過 manRb.setChecked(true) 設定預設選中「男」;再透過 setOnCheckedChangeListener 監聽選擇變化,即時把目前選中的選項文字顯示到上方的 TextView。這樣就完成了一個帶有預設值的單選組。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved