android 复选框横向,android基础-CheckBox(复选框)

CheckBox(复选框)

即可以同时选中多个选项,至于获得选中的值,同样有两种方式: 1.为每个CheckBox添加事件:setOnCheckedChangeListener 2.弄一个按钮,在点击后,对每个checkbox进行判断:isChecked();

布局示例 activity_main.xml

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/LinearLayout1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity" >

android:id="@+id/cbSleep"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="睡觉" />

android:id="@+id/cbSing"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="唱歌" />

android:id="@+id/btnShow"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="输出"

android:onClick="show" />

MainActivity.java

package com.example.myapplication;

import java.util.HashMap;

import java.util.Map;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.Toast;

public class MainActivity extends Activity implements OnCheckedChangeListener {

// 创建map字典用于储存选择的内容

private Map map_dict = new HashMap();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// 获取控件

CheckBox cbSing = (CheckBox) findViewById(R.id.cbSing);

CheckBox cbSleep = (CheckBox) findViewById(R.id.cbSleep);

// 绑定事件

cbSing.setOnCheckedChangeListener(this);

cbSleep.setOnCheckedChangeListener(this);

}

@Override

public void onCheckedChanged(CompoundButton checkBox, boolean checked) {

// 判断是否选中,选中就把数据加入到map字典中,如果都没有的话默认移除mao字典所有数据

switch (checkBox.getId()) {

case R.id.cbSing:

if (checked) {

map_dict.put("sing", "唱歌");

}else {

map_dict.remove("sing");

}

break;

case R.id.cbSleep:

if (checked) {

map_dict.put("sleep", "睡觉");

}else {

map_dict.remove("sleep");

}

break;

default:

break;

}

}

public void show(View v) {

// 判断map字典中是否存在数据

if(map_dict.isEmpty()){

Toast.makeText(MainActivity.this, "没有选中任何数据", Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(getApplicationContext(), "您选中的爱好是:" + map_dict, Toast.LENGTH_SHORT).show();

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值