常用控件
3、checkbox
复选框,确定是否勾选,点击一下勾选,点击第二下取消,当有一系列备选项时适合用checkbox控件,方便用户提交数据。
贴上例子Activity的java代码
1 package com.example.checkbox; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.Menu; 6 import android.widget.CheckBox; 7 import android.widget.CompoundButton; 8 import android.widget.Toast; 9 import android.widget.CompoundButton.OnCheckedChangeListener; 10 import android.widget.TextView; 11 12 public class MainActivity extends Activity implements OnCheckedChangeListener{ 13 14 private CheckBox cb1,cb2,cb3; 15 private TextView tv; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 22 cb1 = (CheckBox)findViewById(R.id.cb1); 23 cb2 = (CheckBox)findViewById(R.id.cb2); 24 cb3 = (CheckBox)findViewById(R.id.cb3); 25 26 cb1.setOnCheckedChangeListener(this); 27 cb2.setOnCheckedChangeListener(this); 28 cb3.setOnCheckedChangeListener(this); 29 30 tv = (TextView)findViewById(R.id.tv); 31 } 32 33 34 @Override 35 public boolean onCreateOptionsMenu(Menu menu) { 36 // Inflate the menu; this adds items to the action bar if it is present. 37 getMenuInflater().inflate(R.menu.main, menu); 38 return true; 39 } 40 41 42 @Override 43 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 44 // TODO Auto-generated method stub 45 if(cb1 == buttonView||cb2 == buttonView||cb3 == buttonView) { 46 if(isChecked) { 47 showToast(buttonView.getText()+"选中"); 48 } else { 49 showToast(buttonView.getText()+"取消"); 50 } 51 } 52 53 } 54 55 public void showToast(String str) { 56 Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); 57 } 58 59 }