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 获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐