1. 程式人生 > >Android RadioGroup單選框變成多選問題

Android RadioGroup單選框變成多選問題

在用RadioButton單選框元件時,變成了多選的問題,先看我的佈局程式碼

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            android:orientation="vertical" >

            <RadioButton
                android:id="@+id/radioButton1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/action_registr" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:orientation="vertical" >

            <RadioButton
                android:id="@+id/radioButton2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/action_settings" />
        </LinearLayout>
    </RadioGroup>

</LinearLayout>

佈局大網



然後是執行後佈局的效果:註冊時預設選中的,設定是預設不選中,理應當我選中設定時,註冊框為不選中,但是出現了圖二問題


圖二:


本身佈局檔案寫好後預設是為單選功能的,但是卻不是。

原因出現在哪裡呢,經過排查問題出現在了兩個線性佈局上,請看圖


這兩個線性佈局導致了單選功能失效,具體沒有深究,應為這樣做也是有需求的,以下是解決這個問題的程式碼

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CompoundButton;
import android.widget.RadioButton;

public class WebViewActivity extends FragmentActivity {
	RadioButton mLeftRadio,mRightRadio;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test);
		mLeftRadio = (RadioButton)findViewById(R.id.radioButton1);
		mRightRadio = (RadioButton)findViewById(R.id.radioButton2);
		mLeftRadio.setOnCheckedChangeListener(mChangeListener);
		mRightRadio.setOnCheckedChangeListener(mChangeListener);
	}
	
	final OnCheckedChangeListener mChangeListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if(buttonView.getId()==R.id.radioButton1 && isChecked){
				T.showShort(getApplication(), "RadioButton1");
				mRightRadio.setChecked(false);
			}else if(buttonView.getId()==R.id.radioButton2 && isChecked){
				T.showShort(getApplication(), "RadioButton2");
				mLeftRadio.setChecked(false);
			}
		}
	};
}

附:其實正常的單選佈局應該是這樣子的 但是這隻能滿足一般的單選框需求