2012-01-27 111 views
0

我有一個名爲options.xml的xml文件 我用它來創建我的AlertDialog。我還爲AlertDialog添加了一個完成按鈕。 按下完成按鈕時,會調用下面的onClick方法。但是,無論單擊完成之前我檢查過哪個RadioButton,我總是將第一個RadioButton選中,其他人選中爲未選中狀態。 我假設我在做什麼,只是讀取xml值而不是實際的運行時間值?那我該如何閱讀真正的運行時間值?如何閱讀RadioButton狀態

public void onClick(DialogInterface arg0, int arg1) { 
      LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ; 
      View layout = inflater.inflate(R.layout.options, null); 
      RadioButton a1 = (RadioButton)layout.findViewById(R.id.radio0); 
      RadioButton a2= (RadioButton)layout.findViewById(R.id.radio1); 
      RadioButton a3 = (RadioButton)layout.findViewById(R.id.radio2); 
      RadioButton a4 = (RadioButton)layout.findViewById(R.id.radio3); 
      boolean b1 = a1.isChecked(); 
      boolean b2 = a2.isChecked(); 
      boolean b3 = a3.isChecked(); 
      boolean b4 = a4.isChecked(); 

    } 

編輯:我用「謝謝你的解決方案,我沒有檢查第二個選項,但我發現,AlertDialog有findViewById,它只是一個調用一個創建對話框後(不是需要成爲問題。在onCreate或任何其他特殊函數中完成)你只需要在調用對話框的show()之後記得調用findViewById,否則它不會工作「

回答

0

你是對的,你正在閱讀的XML他們的價值,因爲你想直接從xml膨脹的佈局上找到ViewById。

如果mContext是一個活動,則可以使用mContext.findViewById(..)。如果不這樣做,請在onCreateDialog(..)中的某處定義您的RadioButton,而不是在onClick(..)中定義您的RadioButton,然後使用它們來確定isChecked()。

這是一個類似的例子,我必須從onClick(..)方法中獲取EditText的值。如果你需要final修飾符,Eclipse應該告訴你。這全部在onCreateDialog(..)方法中。

case FIRST_TRANSLATE: 
     View view = mHost.getLayoutInflater().inflate(R.layout.first_translate, null); 
     //Define your radiobuttons here 
     final EditText mLanguage = (EditText) view.findViewById(R.id.editText1); 
     b.setView(view) 
     .setTitle(R.string.dialog_first_translate_title) 
     .setPositiveButton(sOkay, new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int arg1) { 
       //Retrieve their values here 
       mHost.getSharedPreferences(States.INTERNAL_PREFS, 0).edit().putString("deflang", mLanguage.getText().toString()).commit(); 
       dialog.dismiss(); 
      } 

     }).create(); 
+1

謝謝,我沒有檢查第二個選項,但我發現AlertDialog有findViewById,它只是在創建對話框後調用的問題。 (不需要在onCreate或任何其他特殊功能中完成)。 在調用show()作爲對話框之後,你只需要記得調用findViewById,否則它就不能工作。 – user1097185 2012-01-27 17:41:36