安卓:EditText.getText()的toString()不工作。 [英] Android: EditText.getText().toString() not working

查看:145
本文介绍了安卓:EditText.getText()的toString()不工作。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code建立一个AlertDialog有一个EditText:

I use this code to build an AlertDialog with an EditText:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setView(LayoutInflater.from(context).inflate(R.layout.dialog_view, null));
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        mInput = ((EditText) LayoutInflater.from(context).inflate(R.layout.dialog_view, null).findViewById(R.id.etxtDialog)).getText().toString();
    }
});
builder.show();

当我虽然运行此code时,mInput.length()== 0,因此字符串是空的。 。行 mInput =((EditText上)LayoutInflater.from(上下文).inflate(R.layout.dialog_view,NULL).findViewById(R.id.etxtDialog))的getText()的toString(); 虽然是执行和EditText上确实包含一些字符。为什么不是这个code工作?

When I run this code though, the mInput.length() == 0, so the string is empty. The line mInput = ((EditText) LayoutInflater.from(context).inflate(R.layout.dialog_view, null).findViewById(R.id.etxtDialog)).getText().toString(); is executed though and the EditText does contain some characters. Why isn't this code working?

推荐答案

您这样做是错误的......握住你的放大视图的实例,并在以后使用它。例如:

You are doing it wrong... Hold the instance of your inflated view and use it later. For example:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
final View v = LayoutInflater.from(context).inflate(R.layout.dialog_view, null);
builder.setView(v);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
       mInput = ((EditText)v.findViewById(R.id.etxtDialog)).getText().toString();
    }
});
builder.show();

这篇关于安卓:EditText.getText()的toString()不工作。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆