3.1.6 checkbox控件

3.1.6 checkbox控件

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

</androidx.constraintlayout.widget.ConstraintLayout>

(复选框,当点击发羽毛球,篮球,乒乓球的时候,下面的txexview控件显示选择了什么?)

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

</androidx.constraintlayout.widget.ConstraintLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView textViewResult;
private CheckBox checkBoxBadminton, checkBoxBasketball, checkBoxTableTennis;

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

textViewResult = findViewById(R.id.textViewResult);
checkBoxBadminton = findViewById(R.id.checkBoxBadminton);
checkBoxBasketball = findViewById(R.id.checkBoxBasketball);
checkBoxTableTennis = findViewById(R.id.checkBoxTableTennis);

checkBoxBadminton.setOnCheckedChangeListener((buttonView, isChecked) -> updateTextView());
checkBoxBasketball.setOnCheckedChangeListener((buttonView, isChecked) -> updateTextView());
checkBoxTableTennis.setOnCheckedChangeListener((buttonView, isChecked) -> updateTextView());
}

private void updateTextView() {
StringBuilder selectedHobbies = new StringBuilder("您选择的兴趣爱好为:");
if (checkBoxBadminton.isChecked()) {
selectedHobbies.append("羽毛球 ");
}
if (checkBoxBasketball.isChecked()) {
selectedHobbies.append("篮球 ");
}
if (checkBoxTableTennis.isChecked()) {
selectedHobbies.append("乒乓球 ");
}
textViewResult.setText(selectedHobbies.toString().trim());
}
}

posted @ 2025-03-27 18:28  大胡子编程  阅读(47)  评论(0)    收藏  举报