CheckBox的使用

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <CheckBox 
        android:id="@+id/cb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="first"/>
    <CheckBox 
        android:id="@+id/cb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="second"/>
    <CheckBox 
        android:id="@+id/cb3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="third"/>

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

java对CheckBox的传值

package com.example.assembly;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity implements OnCheckedChangeListener {
	private TextView showTv;
	private String str = "";
	private String str1 = "", str2 = "", str3 = "";
	private CheckBox cb1, cb2, cb3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		showTv = (TextView) findViewById(R.id.show);
		cb1 = (CheckBox) findViewById(R.id.cb1);
		cb2 = (CheckBox) findViewById(R.id.cb2);
		cb3 = (CheckBox) findViewById(R.id.cb3);
		cb1.setOnCheckedChangeListener(this);
		cb2.setOnCheckedChangeListener(this);
		cb3.setOnCheckedChangeListener(this);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.cb1:
			if (isChecked) {
				str1 = "first,";
			} else {
				str1 = "";
			}
			break;
		case R.id.cb2:
			if (isChecked) {
				str2 = "second,";
			} else {
				str2 = "";
			}
			break;
		case R.id.cb3:
			if (isChecked) {
				str3 = "third,";
			} else {
				str3 = "";
			}
			break;
		default:
			break;
		}
		str = str1 + str2 + str3;
		showTv.setText(str);
	}
}

java对CheckBox设值

if (str.contains("first")) {
			cb1.setChecked(true);
		}else {
			cb1.setChecked(false);
		}
		if (str.contains("second")) {
			cb1.setChecked(true);
		}else {
			cb1.setChecked(false);
		}
		if (str.contains("third")) {
			cb1.setChecked(true);
		}else {
			cb1.setChecked(false);
		}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值