Android單選按鈕RadioButton的使用方法
單選按鈕要在一組中選擇一項,并且不能多選。
同一組RadioButton要放在同一個RadioGroup節點下。
RadioButton默認未選中,點擊后選中但是再次點擊不會取消選中。
RadioButton經常會更換按鈕圖標,如果通過button屬性變更圖標,那么圖標與文字就會挨得很近。為了拉開圖標與文字之間的距離,得換成drawableLeft屬性展示新圖標(不要忘記把button改為@null),再設置drawablePadding即可指定間隔距離。
復現代碼時出現了一個錯誤,處理單選按鈕的響應,要先寫一個單選監聽器實現接口 RadioGroup.OnCheckedChangeListener,而不是復合按鈕的CompoundButton.OnCheckedChangeListener。
MainActivity
package com.example.middle; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.RadioGroup;import android.widget.TextView;import android.widget.RadioGroup.OnCheckedChangeListener; public class RadioVerticalActivity extends AppCompatActivity implements OnCheckedChangeListener { private TextView tv_marry; // 聲明一個文本視圖對象 @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_radio_vertical);// 從布局文件中獲取名叫tv_marry的文本視圖tv_marry = findViewById(R.id.tv_marry);// 從布局文件中獲取名叫rg_marry的單選組RadioGroup rg_marry = findViewById(R.id.rg_marry);// 給rg_marry設置單選監聽器,一旦用戶點擊組內的單選按鈕,就觸發監聽器的onCheckedChanged方法rg_marry.setOnCheckedChangeListener(this); } // 在用戶點擊組內的單選按鈕時觸發 public void onCheckedChanged(RadioGroup group, int checkedId) {if (checkedId == R.id.rb_married) { tv_marry.setText('哇哦,祝你早生貴子');} else if (checkedId == R.id.rb_unmarried) { tv_marry.setText('哇哦,你的前途不可限量');} } }
Layout
<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' android:padding='10dp' > <TextViewandroid:layout_width='match_parent'android:layout_height='wrap_content'android:text='請選擇您的婚姻狀況'android:textColor='#000000'android:textSize='17sp' /> <RadioGroupandroid: android:layout_width='match_parent'android:layout_height='wrap_content'android:orientation='vertical' > <!-- 通過button屬性修改單選按鈕的圖標 --><RadioButton android: android:layout_width='wrap_content' android:layout_height='wrap_content' android:padding='5dp' android:button='@drawable/radio_selector' android:text='未婚' android:textColor='#000000' android:textSize='17sp' /> <!-- 通過drawableLeft屬性修改單選按鈕的圖標 --><RadioButton android: android:layout_width='wrap_content' android:layout_height='wrap_content' android:padding='5dp' android:button='@null' android:drawableLeft='@drawable/radio_selector' android:drawablePadding='10dp' android:text='已婚' android:textColor='#000000' android:textSize='17sp' /> </RadioGroup> <TextViewandroid: android:layout_width='match_parent'android:layout_height='wrap_content'android:textColor='#000000'android:textSize='17sp' /></LinearLayout>
result
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. MyBatis JdbcType 與Oracle、MySql數據類型對應關系說明2. .NET SkiaSharp 生成二維碼驗證碼及指定區域截取方法實現3. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )4. django創建css文件夾的具體方法5. ASP中if語句、select 、while循環的使用方法6. jsp網頁實現貪吃蛇小游戲7. 在JSP中使用formatNumber控制要顯示的小數位數方法8. ASP中實現字符部位類似.NET里String對象的PadLeft和PadRight函數9. 存儲于xml中需要的HTML轉義代碼10. 利用CSS制作3D動畫
