RadioButton的單選按鈕;
RadioGroup是單選組合框,用於將RadioButton框起來;
在沒有RadioGroup的情況下,RadioButton可以全部都選中;
當多個RadioButton被RadioGroup包含的情況下,RadioButton只可以選擇一個;
注意:單選按鈕的事件監聽用setOnCheckedChangeListener來對單選按鈕進行監聽
RadioButton效果:
本程序的main.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"
>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radioBlue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="blue"/>
<RadioButton
android:id="@+id/radioRed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="red"/>
</RadioGroup>
</LinearLayout>
RadioButton事件響應setOnCheckedChangeListener
本程序的java源碼:
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.Toast;
public class RadioButtonActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final RadioGroup group = (RadioGroup)findViewById(R.id.radioGroup);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch(checkedId)
{
case R.id.radioBlue:
Toast.makeText(getApplicationContext(), "你選中了藍色按鈕", Toast.LENGTH_LONG).show();
break;
case R.id.radioRed:
Toast.makeText(getApplicationContext(), "你選中了紅色按鈕", Toast.LENGTH_LONG).show();
break;
}
}
});
}
}