当前位置: 代码迷 >> Android >> 从零开始学android<CheckBox多选按钮的使用.8.>
  详细解决方案

从零开始学android<CheckBox多选按钮的使用.8.>

热度:34   发布时间:2016-04-28 06:16:14.0
从零开始学android<CheckBox多选按钮的使用.八.>
CheckBox的主要功能是完成复选框的操作,在用户输入信息的时候,可以一次性选择多个内容,例如:用户在选择个人兴趣爱好的时候一定会存在多个,则此时就直接使用CheckBox即可完成功能。
在Android中如果要想定义复选框,可以使用android.widget.CheckBox类,此类定义如下:
java.lang.Object
   ?android.view.View
     ?android.widget.TextView
       ?android.widget.Button
         ?android.widget.CompoundButton
           ?android.widget.CheckBox
…………………………………………………………毫无美感的分割线…………………………………………………………
直接在配置文件中设置就OK
<?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" >           <TextView     android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="请选择您喜欢的科目"></TextView><CheckBox    android:id="@+id/checkBox1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="语文" /><CheckBox    android:id="@+id/checkBox2"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="数学" /><CheckBox    android:id="@+id/checkBox3"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="英语" /><CheckBox    android:id="@+id/checkBox4"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="物理" /></LinearLayout>


如果想要程序运行时就默认有选中项,就需要在Java文件中配置
package com.example.helloworld;import android.os.Bundle;import android.app.Activity;import android.graphics.Color;import android.widget.Button;import android.widget.CheckBox;import android.widget.TextView;public class MainActivity extends Activity {	private CheckBox ck1,ck2,ck3;//初始化CheckBox	@Override		protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		super.setContentView(R.layout.activity_main);	this.ck1=(CheckBox)super.findViewById(R.id.checkBox1);//获得ck1	this.ck3=(CheckBox)super.findViewById(R.id.checkBox3);//获得ck2	this.ck2=(CheckBox)super.findViewById(R.id.checkBox4);//获得ck3	ck1.setChecked(true);//设置选中	ck2.setChecked(true);//设置选中	ck3.setChecked(true);//设置选中	//默认选中1、3、4项	}	}

更具体的应用大家可以结合API自行设置
下节预报:Spinner下拉列表框的使用


  相关解决方案