test.java
package org.ben.test; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class AndroidTest_Radio_Group_ButtonActivity extends Activity { RadioGroup rGroup; RadioButton rBtn1,rBtn2,rBtn3,rBtn4; TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textview); rGroup = (RadioGroup)findViewById(R.id.rg); rBtn1 = (RadioButton)findViewById(R.id.rb1); rBtn2 = (RadioButton)findViewById(R.id.rb2); rBtn3 = (RadioButton)findViewById(R.id.rb3); rBtn4 = (RadioButton)findViewById(R.id.rb4); rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub if (checkedId == rBtn2.getId()) { DisplayToast("正确答案是:"+ rBtn2.getText() + ",恭喜你,回答正确!"); } else { DisplayToast("请注意,回答错误!"); } } }); } public void DisplayToast(String str) { Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0, 220); toast.show(); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <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/textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/title" /> <RadioGroup android:id="@+id/rg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_x="3px" android:layout_y="54px"> <RadioButton android:id="@+id/rb1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rb1"/> <RadioButton android:id="@+id/rb2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rb2"/> <RadioButton android:id="@+id/rb3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rb3"/> <RadioButton android:id="@+id/rb4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rb4"/>l </RadioGroup> </LinearLayout>