Android studio RadioButton(單選按鈕)


1.基本用法與事件處理:

1)RadioButton(單選按鈕)

如題單選按鈕,就是只能夠選中一個,所以我們需要把RadioButton放到RadioGroup按鈕組中,從而實現 單選功能!先熟悉下如何使用RadioButton,一個簡單的性別選擇的例子: 另外我們可以為外層RadioGroup設置orientation屬性然后設置RadioButton的排列方式,是豎直還是水平~

效果圖:

PS:筆者的手機是Android 5.0.1的,這里的RadioButton相比起舊版本的RadioButton,稍微好看一點~

布局代碼如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="請選擇性別" android:textSize="23dp" /> <RadioGroup android:id="@+id/radioGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <RadioButton android:id="@+id/btnMan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="男" android:checked="true"/> <RadioButton android:id="@+id/btnWoman" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="女"/> </RadioGroup> <Button android:id="@+id/btnpost" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="提交"/> </LinearLayout>

獲得選中的值:

這里有兩種方法,

第一種是為RadioButton設置一個事件監聽器setOnCheckChangeListener

例子代碼如下:

RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup); //第一種獲得單選按鈕值的方法  //為radioGroup設置一個監聽器:setOnCheckedChanged()  radgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton radbtn = (RadioButton) findViewById(checkedId); Toast.makeText(getApplicationContext(), "按鈕組值發生改變,你選了" + radbtn.getText(), Toast.LENGTH_LONG).show(); } });

運行效果圖: 

PS:另外有一點要切記,要為每個RadioButton添加一個id,不然單選功能會生效!!!

第二種方法是通過單擊其他按鈕獲取選中單選按鈕的值,當然我們也可以直接獲取,這個看需求~

例子代碼如下:

Button btnchange = (Button) findViewById(R.id.btnpost); RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup); //為radioGroup設置一個監聽器:setOnCheckedChanged()  btnchange.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { for (int i = 0; i < radgroup.getChildCount(); i++) { RadioButton rd = (RadioButton) radgroup.getChildAt(i); if (rd.isChecked()) { Toast.makeText(getApplicationContext(), "點擊提交按鈕,獲取你選擇的是:" + rd.getText(), Toast.LENGTH_LONG).show(); break; } } } });

運行效果圖:

代碼解析: 這里我們為提交按鈕設置了一個setOnClickListener事件監聽器,每次點擊的話遍歷一次RadioGroup判斷哪個按鈕被選中我們可以通過下述方法獲得RadioButton的相關信息!

  • getChildCount( )獲得按鈕組中的單選按鈕的數目;
  • getChinldAt(i):根據索引值獲取我們的單選按鈕
  • isChecked( ):判斷按鈕是否選中


免責聲明!

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



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