CheckBox就是选择框,这个估计在以后的ListView,很有用,这里感觉并没有什么太大的作用,就是简单的实验,很简单。
主要是响应时间,和button一样,一种是android:onClick,设置这个属性,写一个方法,public void 有个view参数,
然后下面是demo,就可以了,
public void onCheckboxClicked(View view) { // Is the view now checked? boolean checked = ((CheckBox) view).isChecked(); // Check which checkbox was clicked switch(view.getId()) { case R.id.checkbox_meat: if (checked) // Put some meat on the sandwich else // Remove the meat break; case R.id.checkbox_cheese: if (checked) // Cheese me else // I'm lactose intolerant break; // TODO: Veggie sandwich } }
还有就是设置监听,官网没讲,疯狂java用的这个。类似吧
CheckBox box =(CheckBox) findViewById(R.id.checkbox_cheese); box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ Toast.makeText(getApplication(),"123cheese",Toast.LENGTH_SHORT).show(); } // Cheese me else{ Toast.makeText(getApplication(),"123nochesse",Toast.LENGTH_SHORT).show(); } } });
RadioButton,需要有个RadioGroup放着,然后设置点击方式和上面类似
public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked switch(view.getId()) { case R.id.radio_pirates: if (checked) // Pirates are the best break; case R.id.radio_ninjas: if (checked) // Ninjas rule break; } }
RadioButton radioButton = (RadioButton) findViewById(R.id.radio_ninjas); radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ Toast.makeText(getApplication(),"选择了",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplication(),"取消选择了",Toast.LENGTH_SHORT).show(); } } });
有一点,官网说,如果要显示所有的选项用RadioGroup,要是指显示一个,想看多的下拉,用Spinner,这个以后再学。