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



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

以下是如何在自定义对话框中从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();

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

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

最新更新