首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android RadioGroup 添加子視圖:改用 RelativeLayout 而非繼承 RadioButton

     編輯:程式設計綜合問答

問題

RadioGroup 只能直接包含 RadioButton,需在每個 RadioButton 下方顯示 TextView 說明。

方案:放棄 RadioGroup,用 RelativeLayout 模擬單選邏輯

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/rb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 1" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/rb1"
        android:text="Description for option 1" />

    <RadioButton
        android:id="@+id/rb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv1"
        android:text="Option 2" />

    <TextView
        android:layout_below="@id/rb2"
        android:text="Description for option 2" />

</RelativeLayout>

邏輯控制:代碼中實現互斥

RadioButton rb1 = findViewById(R.id.rb1), rb2 = findViewById(R.id.rb2);
rb1.setOnCheckedChangeListener((btn, checked) -> {
    if (checked) rb2.setChecked(false);
});
rb2.setOnCheckedChangeListener((btn, checked) -> {
    if (checked) rb1.setChecked(false);
});

優勢

  • 佈局完全自由,可插入任意視圖。
  • 無需自定義 RadioButton 子類。
  • 易於擴展動畫、分組等高級交互。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved