2012-01-27 114 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