【问题标题】:why cant you retrieve text from EditText widget in Android?为什么不能从 Android 中的 EditText 小部件中检索文本?
【发布时间】:2013-12-16 05:02:17
【问题描述】:

为什么不能从 Android 中的 EditText 小部件中检索文本?即使在 android 开发人员指南上,他们也会玩一个例子,就好像你可以 http://developer.android.com/guide/topics/ui/dialogs.html 他们真的有任何方式吗?因为我想创建一个简单的登录对话框,而程序必须检查用户输入的登录信息,我该怎么做?

【问题讨论】:

    标签: android android-widget widget android-edittext android-studio


    【解决方案1】:

    以下是在自定义对话框中从 EditText 获取文本的方法。

      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      // Get the layout inflater, and inflate the dialog's view (which contains the EditText)
      LayoutInflater inflater = getActivity().getLayoutInflater();
      View dialogView = inflater.inflate(R.layout.dialog_signin, null);
    
      // Keep a reference to the EditText you can use when the user clicks the button
      final EditText editText = (EditText) dialogView.findViewById(R.id.my_edit_text);
    
      // Inflate and set the layout for the dialog
      builder.setView(dialogView)
          // Add action buttons
          .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
              // The user clicked 'ok' or 'sign-in' - now you can get the text from the EditText
              String textFromEditText = editText.getText().toString();
            }
          });
      // Build & show the dialog
      builder.create().show();
    

    【讨论】:

      【解决方案2】:

      为什么不能从 Android 中的 EditText 小部件中检索文本?

      EditText 小部件上调用getText() 以检索文本。它将以CharSequence 的形式返回,我认为从技术上讲是SpannedString 的一个实例。如果您不期望任何格式,请调用 toString() 以获得纯字符串。

      【讨论】:

      • 我试过了,它可以工作,但它不适用于 Dialog blox 内的 EditText 小部件
      • @user3050399:当然可以。您无法使其工作的事实意味着您可能有问题(即在错误的时间点调用它)。这通常就是为什么在问题中提供一些代码被认为是好的做法。它将使我们能够潜在地指出任何错误/误解。没有它,它几乎是在黑暗中拍摄。
      猜你喜欢
      • 2012-06-13
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      相关资源
      最近更新 更多