安卓编程中的CheckBox和RadioButton(纯小白自学嘻嘻)
CheckBox:
CheckBox是同时可以选择多个选项
如何判断CheckBox被选中,选中后如何触发事件
final CheckBox checkBox1 = findViewById(R.id.checkBox1);
checkBox1.setText(“判断是否点击”); //首先将checkBox1的文本内容设置为判断是否点击
checkBox1.setOnClickListener(new View.OnClickListener() {//调用CheckBox的方法setOnClickListener检测是否选择框是否被选中
@Override
public void onClick(View v) {//重写选中触发事件
textViewOfCB1.setText(“secleted:” + checkBox1.isChecked());//若被选中,触发事件:将checkBox1后对用的TextView内容换成secleted: true
}
RadioButton
RadioButton则是仅可以选择一个选项的控件
RadioGroup是RadioButton的承载体,程序运行时不可见,一个RadioGroup可以包含多个RadioButton,在每一个RadioGroup中,用户仅能够选择其中一个RadioButton
RadioGroup在设计时可见,运行时不可见
向RadioGroup中放入两个RadioButton时,默认为vertical(垂直摆放)
选中ButtonGroup在Attribute栏中找到orientation,并设置为horizontal即可变为水平模式
小练习
代码:
package com.example.practice;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textViewOfBasicInfo = findViewById(R.id.textViewOfBasicInfo);
textViewOfBasicInfo.setText("基本信息");
TextView textViewOfName = findViewById(R.id.textVieOfName);
textViewOfName.setText("姓名:");
TextView textViewOfHeight = findViewById(R.id.textViewOfHeight);
textViewOfHeight.setText("身高:");
TextView textViewOfWeight = findViewById(R.id.textViewOfWeight);
textViewOfWeight.setText("体重");
TextView textViewOfCm = findViewById(R.id.textViewOfCm);
textViewOfCm.setText("CM");
TextView textViewOfKg = findViewById(R.id.textViewOfKg);
textViewOfKg.setText("KG");
TextView textViewOfGender = findViewById(R.id.textViewOfGender);
textViewOfGender.setText("性别:");
TextView textViewOfHobby = findViewById(R.id.textViewOfHobby);
textViewOfGender.setText("爱好:");
RadioButton radioButtonOfMan = findViewById(R.id.radioButtonOfMan);
radioButtonOfMan.setText("男");
RadioButton radioButtonOfLady = findViewById(R.id.radioButtonOfLady);
radioButtonOfLady.setText("女");
CheckBox checkBoxOfHobbyOfTravel = findViewById(R.id.checkBoxOfHobbyOfTravel);
checkBoxOfHobbyOfTravel.setText("旅游");
final CheckBox checkBoxOfHobbyOfRun = findViewById(R.id.checkBoxOfHobbyOfRun);
checkBoxOfHobbyOfRun.setText("运动");
CheckBox checkBoxOfHobbyOfTOther = findViewById(R.id.checkBoxOfHobbyOfOther);
checkBoxOfHobbyOfTOther.setText("其他");
final TextView textViewOfOut = findViewById(R.id.textViewOfOut);
textViewOfOut.setText("你的爱好:");
checkBoxOfHobbyOfRun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBoxOfHobbyOfRun.isChecked()) {
textViewOfOut.setText("你的爱好是运动");
}
}
});
}
}