2017-08-28 36 views
-1

我有一個單選按鈕單選按鈕組在一個XML文件:如何在Android中按ID查找單選按鈕?

<?xml version="1.0" encoding="utf-8"?> 
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <RadioButton 
     android:id="@+id/btn_1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onRadioButtonClicked" /> 

    <RadioButton 
     android:id="@+id/btn_2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onRadioButtonClicked" /> 

</RadioGroup> 

我怎樣才能通過ID得到一個單選按鈕?我想:

RadioButton btn = (RadioButton)findViewById(R.id.btn_1) 

但是,這將引發一個NullPointerException當我呼籲btnsetChecked()方法。我錯過了什麼?

+0

單選按鈕BTN =(單選)findViewById(R.id.btn_1) –

回答

2

你只需要調用RadioGroup中對象.findViewById()。如果定義無線電組ID radioGroup你可以這樣訪問各個按鈕:

RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup); 
View radioButton = radioGroup.findViewById(R.id.btn_1); 

其它有用的功能是radioGroup.getChildAt(int)

+0

謝謝。這工作完美 –

1

你沒有在任您單選按鈕

的指向你需要或者:

RadioButton btn = (RadioButton)findViewById(R.id.btn_1); 

RadioButton btn = (RadioButton)findViewById(R.id.btn_2); 
+0

這只是一個錯字,我編輯了這個問題 –

+0

@ToniJoe你能告訴我們你的代碼在Java文件中嗎?您提供的XML並沒有真正給出可能出錯的信息 –

1
RadioGroup rg= (RadioGroup) findViewById(R.id.your_RadioGroud_Id); 
RadioButton rb= rg.findViewById(R.id.btn_1);