无法从EditText上的自定义AlertDialog得到字符串

无法从EditText上的自定义AlertDialog得到字符串

本文介绍了无法从EditText上的自定义AlertDialog得到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在得到有关从自定义AlertDialog文陷入了僵局。我得到一个错误NullPointerException异常。
我提出定义包含在AlertDialog中的EditText变量,但我得到了同样的错误。

I am in an impasse regarding getting the text from a custom AlertDialog. I get an error "NullPointerException".I have moved defining the variable containing the EditText in the AlertDialog, but I get the same error.

在它我的版面项目的XMLpin.xml

My layout item in it's XML "pin.xml"

<EditText
    android:id="@+id/insert_pin"
    android:layout_width="90dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:gravity="center"
    android:inputType="numberPassword"
    android:maxLength="4" />

在AlertDialog

The AlertDialog

        new AlertDialog.Builder(this)
        .setView(inflater.inflate(R.layout.pin, null))
        .setTitle("Save PIN")
        .setPositiveButton("Save", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                pin = (EditText) findViewById(R.id.insert_pin);
                //here I get the Error. Apparently, it can't get the value
                input = pin.getText().toString();

                dialog.cancel();
                go();
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
                finish();
            }
        })
        .show();

任何帮助将大大AP preciated。

Any help would be vastly appreciated.

推荐答案

您已经为你找到使用findViewById()的的EditText Field对象更改code,但你应该findViewById()相对于对话框视图。

you have to change your code as you are find the EditText Field object using findViewById() but you should findViewById() with respect to Dialog View.

更改code如下:

View v = inflater.inflate(R.layout.pin, null);


new AlertDialog.Builder(this)
        .setView(v)
        .setTitle("Save PIN")
        .setPositiveButton("Save", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                pin = (EditText)v.findViewById(R.id.insert_pin);
                //here I get the Error. Apparently, it can't get the value
                input = pin.getText().toString();

                dialog.cancel();
                go();
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
                finish();
            }
        })
        .show();

这篇关于无法从EditText上的自定义AlertDialog得到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:41