• 了解Android_05之RadioButton


    一、RadioButton是什么?

      字面翻译即单选按钮。

    二、RadioButton样式:

    <RadioGroup
            android:id="@+id/rg1"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:orientation="horizontal"
        >
            <RadioButton
                android:id="@+id/rb1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="男"
                android:textSize="34sp"
                android:button="@null"
                android:checked="true"
                android:background="@drawable/radio_button"
                android:layout_weight="1"
                android:gravity="center"
            />
            <RadioButton
                android:id="@+id/rb2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="女"
                android:textSize="34sp"
                android:button="@null"
                android:background="@drawable/radio_button"
                android:layout_weight="1"
                android:gravity="center"
            />
        </RadioGroup>

    分析:

     自定义样式xml:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true">
            <shape>
                <solid android:color="#E6941A"/>
                <corners android:radius="8dp"/>
            </shape>
        </item>
        <item android:state_checked="false">
            <shape>
                <stroke
                    android:color="#E6941A"
                    android:width="1dp"
                />
                <corners android:radius="8dp"/>
            </shape>
        </item>
    </selector>

    由于我这里使用的是真机调试,效果不好展示,效果为按钮被选中时填充一个橘色,未选中时为描边的样式:

     三、选中时触发的事件:

    public class MainActivity extends AppCompatActivity {
        private RadioGroup rg1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            rg1 = findViewById(R.id.rg1);
            rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int i) {
                    RadioButton rb = radioGroup.findViewById(i); //通过单选按钮组来获取被选中的单选按钮
                    Toast.makeText(MainActivity.this,rb.getText(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
  • 相关阅读:
    C++异常第二篇---C++标准库异常类exception的使用
    C++异常(exception)第一篇--综合讲解
    libconfig第二篇----两个小例子
    libconfig第一篇———使用指南
    log4cxx第三篇----使用多个logger
    kafka第五篇
    kafka第四篇--快速入门(如何使用kafka)
    UVA 455(最小周期)
    UVA1584(环状序列)
    UVA1583(最小生成元)
  • 原文地址:https://www.cnblogs.com/wmskywm/p/13866429.html
Copyright © 2020-2023  润新知