Android - Custom Dialog - Can#39;t get text from EditText(Android - 自定义对话框 - 无法从 EditText 获取文本)
问题描述
我的自定义对话框有问题.
我的对话框由 TextView
、EditText
和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 获取文本
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01