checkbox 方法运用

来源:互联网 发布:斗鱼手机客户端无网络 编辑:程序博客网 时间:2024/05/17 07:16

xml  文件


<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.administrator.xuexi.MainActivity">    <CheckBox        android:checked="false"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="足球"        android:id="@+id/checkBox"        android:layout_alignParentTop="true"        android:layout_alignParentStart="true" /></RelativeLayout>


java


package com.example.administrator.xuexi;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    private CheckBox checkBox;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        checkBox =(CheckBox)findViewById(R.id.checkBox);        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {                //通过OnCheckedChanged来监听当前的checkBox是否被选中                if (b){                    //获得checkbox的文本内容                   String text = checkBox.getText().toString();                    Toast toast=Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT);                    toast.show();                }            }        });    }}

0 0