从零开始学android:Android事件处理—单选钮与OnCheckedChangeListener

来源:互联网 发布:类似记事本的软件 编辑:程序博客网 时间:2024/05/16 05:42

OnCheckedChangeListener

单选钮(RadioGroup)上也可以进行事件的处理操作,当用户选中了某选项之后也将触发相应的监听器进行若干处理,而注册事件的方法为:
public void setOnCheckedChangeListener (RadioGroup.OnCheckedChangeListener listener)。

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView         android:id="@+id/show"        android:text="您的姓名是:"        android:textSize="20px"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        />    <RadioGroup         android:id="@+id/sex"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="vertical"        android:checkedButton="@+id/male"        >        <RadioButton             android:id="@+id/male"            android:text="男"            />        <RadioButton             android:id="@+id/female"            android:text="女"            />    </RadioGroup></LinearLayout>

程序文件:

package com.richard.onclickedchangelistener;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.RadioGroup.OnCheckedChangeListener;import android.widget.TextView;public class MainActivity extends Activity {private TextView show = null;private RadioGroup sex = null;private RadioButton male = null;private RadioButton female = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);this.show = (TextView) super.findViewById(R.id.show);this.sex = (RadioGroup) super.findViewById(R.id.sex);this.male = (RadioButton) super.findViewById(R.id.male);this.female = (RadioButton) super.findViewById(R.id.female);this.sex.setOnCheckedChangeListener(new OnCheckedChangeListenerImpl());}private class OnCheckedChangeListenerImpl implements OnCheckedChangeListener{@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {String temp = null;if(MainActivity.this.male.getId() == checkedId){temp = MainActivity.this.male.getText().toString();//取得单选文本}if(MainActivity.this.female.getId() == checkedId){temp = MainActivity.this.female.getText().toString();//取得单选文本}MainActivity.this.show.setText("您的性别是:"+temp);//设置文本信息}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

 测试效果:


原创粉丝点击