从非活动调用时,findViewById返回null

时间:2013-03-24 03:55:26

标签: android scala

我正在尝试使用Scala开发Android应用程序。

当我的应用程序启动时,它会立即显示如下对话框:

override def onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)   
    competitionSetupDialogFragment.show(getFragmentManager(), HomeScreenActivity.CompetitionDialog)
  }  

  override def onStart() {
    super.onStart
    resourceHelper.setActivity(this)
  }

我的片段如下:

class CompetitionSetupDialogFragment extends DialogFragment {
  @Inject
  var competitionSetupDialogHandler: CompetitionSetupDialogHandler = null
  @Inject
  var resourceHelper: ResourceHelper = null

  override def onCreateDialog(savedInstanceState: Bundle): Dialog = {
    val builder = new AlertDialog.Builder(getActivity())
    builder.setMessage(getString(R.string.competitionSetupDialogMessage))
      .setCancelable(false)
      .setView(getActivity().getLayoutInflater.inflate(R.layout.competition_setup, null))
      .setNegativeButton(R.string.cancel, new OnClickListener {
        def onClick(dialog: DialogInterface, which: Int) {
          dismiss()
        }
      })
      .setPositiveButton(R.string.create, new OnClickListener {
        def onClick(dialog: DialogInterface, which: Int) {
          val competitionNameInput = resourceHelper.findViewById(R.id.competitionNameInput).asInstanceOf[EditText]
          val numberOfPlayersInput = resourceHelper.findViewById(R.id.numberOfPlayersInput).asInstanceOf[EditText]
          val numberOfSubsInput = resourceHelper.findViewById(R.id.numberOfSubsInput).asInstanceOf[EditText]
          val lengthOfHalfInput = resourceHelper.findViewById(R.id.lengthOfHalfInput).asInstanceOf[EditText]
          competitionSetupDialogHandler.retrieveValuesAndSave(competitionNameInput, numberOfPlayersInput, numberOfSubsInput, lengthOfHalfInput)
        }
      })

    builder.create()
  }
}

最后,ResourceHelper包含以下内容:

public View findViewById(int viewID) {
        return activity.findViewById(viewID);
    }

我的问题是我的resourceHelper.findViewById总是返回null,即使这些是有效的视图。

我的想法是,当调用onClick()时,视图已被破坏,或类似的东西。 我怎样才能解决这个问题?

这里要添加的一件事是我的对话框显示正常,只有在执行onClick时才会出现问题

1 个答案:

答案 0 :(得分:1)

解决方法如下:

创建了一个对话框视图变量:

var dialogView = getActivity().getLayoutInflater.inflate(R.layout.competition_setup, null)

使用此变量调用findViewById:

val competitionNameInput = dialogView .findViewById(R.id.competitionNameInput).asInstanceOf[EditText]