方法中有EditText的AlertDialog:本地变量EditText可能还没有初始化



在我的应用程序中,我使用AlertDialog与EditText。我想把这段代码移到方法中,因为它被调用了几次。我尝试这样实现它:

private EditText showEditAlert(DialogInterface.OnClickListener listener) {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle(R.string.waypoint);
    alert.setMessage(R.string.waypoint_alert_text);
    EditText editText = new EditText(this);
    alert.setView(editText);
    alert.setPositiveButton(android.R.string.ok, listener);
    alert.setNegativeButton(android.R.string.cancel, null);
    alert.show();
    return editText;
}

然后我想使用它:

final EditText editText = showEditAlert(new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Here is I am working with editText
        // and here is I get error "The local variable editText may not have been initialized"
    }
});

但我得到"本地变量editText可能没有被初始化"错误。据我所知,编译器认为onClick()方法将在showEditAlert()返回值之前调用。

如何正确实现这一点?或者我可以直接抑制这个错误?

看起来IDE的警告正是您所假设的原因。我猜您可以通过为侦听器定义一个自定义接口来规避这个问题(这样使用起来可能会更清楚)。比如:

interface EditAlertOkListener
{
    void onEditAlertOk(EditText editText);
}
private void showEditAlert(final EditAlertOkListener listener)
{
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    ...
    final EditText editText = new EditText(this);
    alert.setView(editText);
    alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            if (listener != null)
                listener.onEditAlertOk(editText);
        }
    }); 
    alert.setNegativeButton(android.R.string.cancel, null);
    alert.show();
}

然后用:

    showEditAlert(new EditAlertOkListener() {
        @Override
        public void onEditAlertOk(EditText editText) {
            // Use editText here.
        }
    });     

p。您还可以让该方法返回EditText,如果需要,我只是删除了它,使这个示例更清晰。或者,如果你只需要EditText内容,让接口传递一个CharSequenceString,而不是EditText本身。这只是一个模板。:)

因为editText变量可能没有初始化。IDE在创建时无法检查。

解决方法是使用关键字:"this"

final EditText editText = showEditAlert(new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        this.getText();// this mean editText, not its parent, if you want to use parent, you must have ParentClass.this
    }
});

最新更新