单选按钮 - 使用不同的公式

问题描述 投票:0回答:1

我刚刚开始,想要制作一个程序,让我的生活更轻松。我需要进行一些数学运算。为此,我需要2个单选按钮:2个月和3个月:

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#FFA24D"
    android:orientation="horizontal" >

    <RadioButton
        android:id="@+id/radio_2m"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_weight="1"
        android:text="2 month"
        android:checked="false" />

    <RadioButton
        android:id="@+id/radio_3m"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_weight="1"
        android:text="3 month"
        android:checked="false" />
</RadioGroup>

我想在选择2个月时执行单件代码(数学公式和东西),并在选择3个月时执行其他代码(其他公式)。我怎么做?

提前致谢。

java android android-studio radio-button radio-group
1个回答
0
投票

在代码中做一些“级联”if语句。首先,您需要获得对布局中定义的视图的引用(使用findViewById(R.id.radio_2m)等),然后您可以使用radioButton.isChecked()来告诉您是否选中了单选按钮。

if(radiobutton1.isChecked()) {
    // The first radio button was checked
}
else {
    // The other radio button was checked.
}

这是有效的,因为您自动包装两个单选按钮的RadioGroup确保一次只检查其中一个子单选按钮。您还应该在xml中设置一个单选按钮以进行检查,因为默认情况下应该选择一个。

© www.soinside.com 2019 - 2024. All rights reserved.