选框的属性

1.在java代码中的属性

  checkBox.setChecked(false) 设置当前的状态

  checkBox.isChecked() 获取当前的状态

  设置当前的监听状态 

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d(TAG, "onCheckedChanged:" + isChecked);
                //当状态被改变的时候, 可以处理很多的数据和UI
            }
        });

2.xml中的属性 

  android:checked="true" 设置当前的状态是true 

java代码

package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CheckBox checkBox = findViewById(R.id.checkBox);
        //设置是否选中(设置它的状态)
        checkBox.setChecked(false);
        //获取它的状态(是否选中)
        boolean isChecked = checkBox.isChecked();

        Log.d(TAG, "onCreate, isChecked:" + isChecked);

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d(TAG, "onCheckedChanged:" + isChecked);
                //当状态被改变的时候, 可以处理很多的数据和UI
            }
        });

    }
}

xml界面代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">


    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="CheckBox" />

</LinearLayout>

posted on 2021-03-16 23:34  python我的最爱  阅读(1816)  评论(0编辑  收藏  举报