Android之checkbox使用

在布局中加上CheckBox标签,给每一个CheckBox注册单独的事件。定义单击事件处理Checkbox



    

    

    

    

    


package com.example.android_checkbox;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	//注册监听事件onCheckboxClicked事件
	public void onCheckboxClicked(View view){
		//判断哪一个CheckBox被选中
		CheckBox chexkBox=((CheckBox)view);
		boolean isCheck=chexkBox.isChecked();
		switch(view.getId()){
		case R.id.checkBox1:
			if(isCheck){
				//可以放到一个容器中,存储复选框选择的item
				Toast.makeText(MainActivity.this, "checkBox1"+chexkBox.getText(), 1).show();
			}else{
				//如果不选中,则从复选框中删除item
			}
			break;
		case R.id.checkBox2:
			if(isCheck){
				Toast.makeText(MainActivity.this, "checkBox2"+chexkBox.getText(), 1).show();
			}else{
				
			}
			break;
		case R.id.checkBox3:
			if(isCheck){
				Toast.makeText(MainActivity.this, "checkBox3"+chexkBox.getText(), 1).show();
			}else{
				
			}
			break;
		case R.id.checkBox4:
			if(isCheck){
				Toast.makeText(MainActivity.this, "checkBox4"+chexkBox.getText(), 1).show();
			}else{
				
			}
			break;
		}
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

运行效果图

Android之checkbox使用_第1张图片

你可能感兴趣的:(Android)