您的位置:首页 > 移动开发 > Android开发

Android 开发 实现复选

2015-07-15 21:43 417 查看
复选中,通过CheckBox控件实现,CheckBox是Button的一个子类,可以继承Button的属性

布局xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choose"
android:height="50px"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ch1"
android:text="ch1"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ch2"
android:text="ch2"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ch3"
android:text="ch3"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update"
android:id="@+id/update"/>
</LinearLayout>


MainActivity

需要监听CheckBox的选中状态,以及点击其它Button时,读取已选中CheckBox的内容

package com.p3_3;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CompoundButton.OnCheckedChangeListener checkbox_listenner = new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked){
Log.i("choosed",compoundButton.getText().toString());
}
}
};
final CheckBox ch1 = (CheckBox)findViewById(R.id.ch1);
final CheckBox ch2 = (CheckBox)findViewById(R.id.ch2);
final CheckBox ch3 = (CheckBox)findViewById(R.id.ch3);
ch1.setOnCheckedChangeListener(checkbox_listenner);
ch2.setOnCheckedChangeListener(checkbox_listenner);
ch3.setOnCheckedChangeListener(checkbox_listenner);

Button button = (Button)findViewById(R.id.update);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String choose = "";
if(ch1.isChecked()){
choose+=ch1.getText().toString()+" ";
}
if(ch2.isChecked()){
choose+=ch2.getText().toString()+" ";
}
if(ch3.isChecked()){
choose+=ch3.getText().toString()+" ";
}
Toast.makeText(MainActivity.this,choose,Toast.LENGTH_SHORT).show();
}
});
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: