Android - 自定义对话框 - 无法从 EditText 获取文本

Android - Custom Dialog - Can#39;t get text from EditText(Android - 自定义对话框 - 无法从 EditText 获取文本)
本文介绍了Android - 自定义对话框 - 无法从 EditText 获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我的自定义对话框有问题.
我的对话框由 TextViewEditText 和Ok"按钮组成.单击确定"后,它应该从 EditText 字段中获取文本并将其分配给 Activity 中定义的字符串变量名称".
一切似乎都正常,没有错误等,但是文本"始终是一个空字符串.
我阅读了一些有关此类问题的主题,但是我不确定我应该在这里进行哪些调整.
我对 Android 编程很陌生,所以如果有人能向我解释这个问题,我将不胜感激.提前致谢.

I have a problem with a custom dialog.
My dialog consists of a TextView, EditText and an "Ok" Button. After clicking "Ok", it should get the text from EditText field and assign it to the String variable "name" defined in the Activity.
Everything seems to work, no errors etc, however "text" is always an empty String.
I read some topics about such problems, however I'm not really sure what adjustments I should make here.
I'm quite new to Android programming, so I'd be grateful if somebody could explain the problem to me. Thanks in advance.

     final Dialog dialog = new Dialog(MyActivity.this);
     dialog.setContentView(R.layout.custom_dialog);
     dialog.setTitle("Title");

     final View layout = View.inflate(this, R.layout.custom_dialog, null);
     Button button = (Button) dialog.findViewById(R.id.dialog_ok);
     button.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
                EditText edit=(EditText)layout.findViewById(R.id.dialog_edit);
                String text=edit.getText().toString();

                name=text;

                dialog.dismiss();
         }
     });   

     dialog.show();

推荐答案

您正在对不需要的布局进行膨胀.如您所见,我修复了您的代码,我删除了您的膨胀行并更改了您尝试查找 EditText 视图的行.

You are inflating a layout where it is not needed. I fixed your code as you see I removed your line where it inflates and changed the line where you try to find the EditText view.

final Dialog dialog = new Dialog(MyActivity.this);
 dialog.setContentView(R.layout.custom_dialog);
 dialog.setTitle("Title");

 Button button = (Button) dialog.findViewById(R.id.dialog_ok);
 button.setOnClickListener(new OnClickListener() {
     public void onClick(View v) {

            EditText edit=(EditText)dialog.findViewById(R.id.dialog_edit);
            String text=edit.getText().toString();

            dialog.dismiss();
            name=text;

     }
 });   


dialog.show();

这篇关于Android - 自定义对话框 - 无法从 EditText 获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent enter key on EditText but still show the text as multi-line(防止在 EditText 上输入键,但仍将文本显示为多行)
Android keyboard next button issue on EditText(EditText上的Android键盘下一个按钮问题)
When the soft keyboard appears, it makes my EditText field lose focus(当软键盘出现时,它使我的 EditText 字段失去焦点)
android how to make text in an edittext exactly fixed lines(android如何在edittext中制作文本完全固定的行)
How to use regular expression in Android(如何在 Android 中使用正则表达式)
Filter list view from edit text(从编辑文本中过滤列表视图)