2017-08-28 6 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) 

をしかし、私はbtnsetChecked()メソッドを呼び出すときに、これは、NullPointerExceptionがスローされます。私は何か見落としてますか?

+0

のRadioButton BTN =(ラジオボタン)findViewById(R.id.btn_1) –

答えて

2

は、あなただけのRADIOGROUPオブジェクトの.findViewById()を呼び出す必要があります。あなたはradioGroupとしてラジオグループIDを定義する場合は、このように、個々のボタンにアクセスすることができます。

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);