java - 对话框和 edittext 监听器 : crash at setEnabled

标签 java android xml button android-edittext

你好,我很想知道这个对话框中的问题出在哪里。我正在尝试在 edittext 中创建一个对话框。如果 edittext 为空,则必须禁用肯定的 button 否则启用。我写了这段代码。

public class Example extends AlertDialog {

    AlertDialog.Builder builder;
    EditText mEditText;
    Context mContext;
    Button button;
    String text;

    protected Example(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        builder = new AlertDialog.Builder(context);
        this.mContext = context;
        mEditText = new EditText(mContext);
        builder.setView(mEditText);
        builder.setPositiveButton("Okay", null);
        builder.setNegativeButton("No", null);

        mEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                AlertDialog dialog = builder.create();

                text = mEditText.getText().toString();

                if(text.trim().length()>0) {

                    button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);

                    if(button != null)
                    button.setEnabled(true);

                    else
                        button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                        button.setEnabled(false);
                }

                else
                    button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    button.setEnabled(false);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }

        });

        builder.setTitle("Example Dialog");
        builder.create();
        builder.show();

    }
}

当我执行这段代码并在 edittext 中写一些东西时,我在 if 中的 else 中得到了 NullPointerException 在此行 button.setEnabled(false); 哪里出了问题?

最佳答案

if 和 else 的作用域只到下一个语句。如果您想使用多个语句而不是将其包含在 block 中。例如-

else
{
button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
}

关于java - 对话框和 edittext 监听器 : crash at setEnabled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20867021/

相关文章:

java - CentOS Java 应用程序出现 SELinux 错误

android - 在代码中将 View 添加到现有的 xml View 组

xml - 在具有命名空间的函数中查询 XML 数据

java - HTML CDATA 问题

java - 哦,不,不再 - 比较两碗矮牵牛 - 对不起 - 漂浮,为了平等

java - 覆盖数据流中的 AvroIO 默认编码器

java - 如何管理大型项目验收测试的测试数据治具?

android - 相对布局中的 z-index

android - 在后台振动电话

android - 开始逐帧动画