Android 中的几个常用控件
如何对RadioGroup添加监听事件?
可能有人会问了,为什么不对RadioButton添加监听事件,而要对RadioGroup添加监听事件呢?因为,处于同一个RadioGroup中的RadioButton,同时只能有一个被选中Checked,我们只需要对RadioGroup进行监听,就可以实现对该组所有RadioButton的监听。另一个重要的原因,大家查看一下RadioButton、RadioGroup在javadoc中的类说明。其中,RadioGroup实现了一个接口 RadioGroup.OnCheckedChangeListener, 通过该接口来实现对一组RadioButton的监听工作。
设置监听事件的代码如下:
import android.widget.RadioGroup;import android.widget.RadioButton;import android.widget.Toast;final RadioButton femaleButton = (RadioButton)findViewById(R.id.femaleRadio);final RadioButton maleButton = (RadioButton)findViewById(R.id.maleRadio);final RadioGroup genderGroup = (RadioGroup)findViewById(R.id.genderGroup);genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkid) { // TODO Auto-generated method stub if (checkid == femaleButton.getId()) { Toast.makeText(MyActivity.this, "I am female.", Toast.LENGTH_SHORT).show(); } else if (checkid == maleButton.getId()) { Toast.makeText(MyActivity.this, "I am male.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MyActivity.this, "Unknown", Toast.LENGTH_SHORT).show(); } } });
在代码中,监听事件onCheckedChanged的第二个参数表示是当前被选中的RadioButton的Id。
2、CheckBox
CheckBox是多选按钮,它与其他的CheckBox不存在冲突的问题,可以同时选中两个或两个以上的CheckBox,因此在CheckBox中没有分组的概念。如果需要对CheckBox添加监听事件,则直接对CheckBox添加监听事件。
如何添加CheckBox到一个活动中?
这个就不用多说了,你可以直接编辑XML文件进行添加;当然你也可以通过布局的可视化视图,直接拖拽视图,并设置其参数。
如何添加CheckBox的监听事件?
在添加事件之前,首先关注一下CheckBox的直接父类:
java.lang.Object
? android.view.View
? android.widget.TextView
? android.widget.Button
? android.widget.CompoundButton
? android.widget.CheckBox
CompoundButton实现了一个接口函数CompoundButton.OnCheckedChangeListener。那CheckBox可以直接继承其父类的接口,添加CompoundButton.OnCheckedChangeListener监听函数。
final CheckBox checkBox = (CheckBox)findViewById(R.id.checkBox);checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton checkBox, boolean checked) { // TODO Auto-generated method stub Toast.makeText(Helloworld.this, "I am a CheckBox", Toast.LENGTH_SHORT).show(); }});
监听事件onCheckedChanged中的第二个参数checked,表示当前点击的CheckBox是否为选中(Checked)状态。
注意:如果一个Activity中存在多个CheckBox,我们需要为每个CheckBox都各自添加一个监听事件。
3、Toast
Toast是一个短时间显示的提示对话框。使用方法非常简单:
public static Toast makeText (Context context, CharSequence text, int duration)Since: API Level 1Make a standard toast that just contains a text view.Parameterscontext The context to use. Usually your Application or Activity object.text The text to show. Can be formatted text.duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG
给一个简单的例子吧:
Toast.makeText(Helloworld.this, "I am a CheckBox", Toast.LENGTH_SHORT).show();
这句执行的操作是:在活动Helloworld的下方,显示一串提示信息,信息的内容是“I am a CheckBox”,显示的时间较短,过一会儿会自动消失。如果将第三个参数修改为"Toast.LENGTH_LONG",那么显示的时间会稍微长一些,但是最后依然会自动消失。
?
