Android学习笔记之RadioButton(RadioGroup)

RadioButton(单选按钮)在Androi发中应用的非常广泛,比如一些选择项的时候,会用到单选按钮。它是一种单个圆形单选框双状态的按钮,可以选择或不选择。在RadioButton没有被选中时,用户能够按下或点击来选中它。但是,与复选框相反,用户一旦选中就不能够取消选中。

实现RadioButton由两部分组成,也就是RadioButton和RadioGroup配合使用.RadioGroup是单选组合框,可以容纳多个RadioButton的容器.在没有RadioGroup的情况下,RadioButton可以全部都选中;当多个RadioButton被RadioGroup包含的情况下,RadioButton只可以选择一个。并用setOnCheckedChangeListener来对单选按钮进行监听

main.xml


RadioGroupActivity.java

通过控件的ID来得到代表控件的对象

然后为RadioGroup设置监听器

package Android.Activity; import android.app.Activity; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class RadioGroupActivity extends Activity { /** Called when the activity is first created. */ private RadioButton maleButton = null; private RadioButton femaleButton = null; private RadioGroup radiogroup =null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //通过控件的ID来得到代表控件的对象 maleButton = (RadioButton)findViewById(R.id.male); femaleButton = (RadioButton)findViewById(R.id.female); radiogroup = (RadioGroup)findViewById(R.id.radiogroup); //为RadioGroup设置监听器,需要注意的是,这里的监听器和Button控件的监听器有所不同 radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub if(femaleButton.getId() == checkedId){ Toast.makeText(RadioGroupActivity.this, "female", Toast.LENGTH_SHORT).show(); } else if(maleButton.getId() == checkedId){ Toast.makeText(RadioGroupActivity.this, "male", Toast.LENGTH_SHORT).show(); } } }); } }


你可能感兴趣的:(Android学习笔记之RadioButton(RadioGroup))