安卓课程二十 CheckBox复选框控件使用

linelayout.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" >
	<Button android:layout_width="fill_parent" android:layout_height="wrap_content"
	    android:id="@+id/buton" android:text="@string/button">
	</Button>
</LinearLayout>

 checkbox.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
</CheckBox>

 MainActivity.java

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;

public class MainActivity extends Activity  implements OnClickListener{

	private List <CheckBox> checkboxs = new ArrayList<CheckBox> (); 
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main);
		String[] chekcBoxTexts = new String[]{"旅游","读书","看书","爬山","踢足球","打篮球","打乒乓球"};
		//动态加载布局
		LinearLayout linerLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.linelayout, null) ;
		for(int i=0;i< chekcBoxTexts.length;i++){
			String item = chekcBoxTexts[i];
			//动态创建布局
			CheckBox checkbox = (CheckBox) getLayoutInflater().inflate(R.layout.checkbox, null);
			checkbox.setText(item);
			checkboxs.add(checkbox);
			
			linerLayout.addView(checkbox, i);
		}
		setContentView(linerLayout);
		
		Button button = (Button) this.findViewById(R.id.buton);
		button.setOnClickListener(this) ;
	}

	@Override
	public void onClick(View v) {
		StringBuffer s = new StringBuffer();
		for(CheckBox box : checkboxs){
			if(box.isChecked()){
				if(s.length()>0){s.append("\n");}
				s.append(box.getText()) ;
			}
		}
		if(s.length()==0){
			s.append("您还没有选择呢");
		}
		//使用提示框提示用户信息
		new AlertDialog.Builder(this).setMessage(s.toString()).setPositiveButton("关闭", null).show() ;
		
	}
}

相关推荐