Android控件之-RadioGroup和RadioButton

單項選擇的組件一般情況是有RadioGroup和RadiaButton組成的

package com.ko8e;

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 Activity01 extends Activity {
    /** Called when the activity is first created. */
	private TextView textView = null;
	private RadioButton button1 = null;
	private RadioButton button2 = null;
	private RadioButton button3 = null;
	private RadioButton button4 = null;
	private RadioGroup group = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.button1);
        button1 = (RadioButton) findViewById(R.id.button1);
        button2 = (RadioButton) findViewById(R.id.button2);
        button3 = (RadioButton) findViewById(R.id.button3);
        button4 = (RadioButton) findViewById(R.id.button4);
        group = (RadioGroup) findViewById(R.id.group);

       group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if(checkedId == button3.getId()) {
					DisplayToast("回答正確!" + button3.getText().toString());
				} else {
					DisplayToast("回答錯誤,請重新選擇");
				}
			}
		});
    }
    public void DisplayToast(String str) {
    	Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
    	toast.setGravity(Gravity.TOP, 0, 200);
    	toast.show();
    }
}

 

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
	android:id="@+id/view"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/question"
    />
<RadioGroup
	android:id="@+id/group"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	android:layout_x="3px"
	android:layout_y="54px"
	/>
<RadioButton
	android:id="@+id/button1"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="@string/button1"
	/>
	<RadioButton
	android:id="@+id/button2"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="@string/button2"
	/>
	<RadioButton
	android:id="@+id/button3"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="@string/button3"
	/>
	<RadioButton
	android:id="@+id/button4"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="@string/button4"
	/>

</LinearLayout>
發佈了36 篇原創文章 · 獲贊 0 · 訪問量 785
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章