Android-RadioButton

1.控件RadioButton需要用RadioGroup包裹起来,才能使用
2.RadioButton必须设置ID才能实现单选功能
3.RadioGroup有方向(垂直方向 和 水平方向)默认是水平方向(像LinearLayout)

Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- RadioGroup RadioButton -->
    <RadioGroup
        android:id="@+id/rg_sex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/rb_man"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男"
            />

        <RadioButton
            android:id="@+id/rb_woman"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女"
            />

    </RadioGroup>

</LinearLayout>

监听事件:

package liudeli.ui.all;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class WidgetActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_widget);

        // RadioButton
        RadioGroup rgSex = findViewById(R.id.rg_sex);
        RadioButton rb_man = findViewById(R.id.rb_man);
        RadioButton rb_woman = findViewById(R.id.rb_woman);

        // 默认设置为男选中状态
        rb_man.setChecked(true);

        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_man:
                        alertToast("男");
                        break;
                    case R.id.rb_woman:
                        alertToast("女");
                        break;
                }
            }
        });

    }

    private void alertToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}




猜你喜欢

转载自www.cnblogs.com/android-deli/p/10099002.html