3.22

所花时间(包括上课):1.5

打码量(行):500

博客量(篇):1

了解到知识点:学习复选框和开关按钮

<CheckBox

    android:id="@+id/checkbox"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Enable Feature X"

    android:checked="false" />

import android.os.Bundle;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    private CheckBox checkBox;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        checkBox = findViewById(R.id.checkbox);

 

        // 设置复选框状态变化的监听器

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {

                    // 复选框被选中

                    Toast.makeText(MainActivity.this, "Feature X enabled", Toast.LENGTH_SHORT).show();

                } else {

                    // 复选框被取消选中

                    Toast.makeText(MainActivity.this, "Feature X disabled", Toast.LENGTH_SHORT).show();

                }

            }

        });

    }

}

<!-- activity_main.xml -->

<Switch

    android:id="@+id/switch_button"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Enable Feature Y"

    android:checked="false" />

import android.os.Bundle;

import android.widget.CompoundButton;

import android.widget.Switch;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    private Switch switchButton;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        switchButton = findViewById(R.id.switch_button);

 

        // 设置开关按钮状态变化的监听器

        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {

                    // 开关按钮被打开

                    Toast.makeText(MainActivity.this, "Feature Y enabled", Toast.LENGTH_SHORT).show();

                } else {

                    // 开关按钮被关闭

                    Toast.makeText(MainActivity.this, "Feature Y disabled", Toast.LENGTH_SHORT).show();

                }

            }

        });

    }

}

posted @ 2024-03-22 17:44  赵千万  阅读(3)  评论(0编辑  收藏  举报