Android多选与单选效果的实现
2017-02-24 本文已影响0人
CrazyBoomer
CheckBox实现多选效果
1.在xml文件中建立CheckBox
<CheckBox android:id="@+id/cbox"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="bt1"
android:checked="true"/>
//可设置多个CheckBox
2.在Activity中初始化操作
public class MainActivity extends Activity {
private CheckBox cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb = (CheckBox) findViewById(R.id.cbox);
}
3.通过匿名内部类方式设置监听器
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i("tag", isChecked+" ");//每次ChexkBox被触摸时的操作
// TODO Auto-generated method stub
if(isChecked){//此次触摸后,CheckBox处于被按下时的操作
String st = cb.getText().toString();
Log.i("tag",st);
}
}});
二.通过RadioButton和RadioGrop实现单选效果
1.在xml文件中建立RedioGrop
<RadioGroup
android:id="@+id/rg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<RadioButton
android:id="@+id/r1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RB1" />
<RadioButton
android:id="@+id/r2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RB2" />
</RadioGroup>
2.在Activity 中初始化操作
public class MainActivity extends Activity{
private RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rg = (RadioGroup) findViewById(R.id.rg1);
rg.setOnCheckedChangeListener(this);
}
}
3.通过接口方式设置监听器
public class MainActivity extends Activity implements OnCheckedChangeListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rg = (RadioGroup) findViewById(R.id.rg1);
rg.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){//判定不同的RadioButton被按下并执行响应操作
case R.id.r1:
Log.i("tag","r1");
break;
case R.id.r2:
Log.i("Tag", "r2");
break;
}
}
}