创建包含无法正常工作的edittext内部的对话框

时间:2014-01-01 16:09:44

标签: java android xml

我想在editext中创建一个简单的对话框。如果edittext为空,则肯定按钮必须是无法选择的。我写这段代码

public class Example extends AlertDialog {

    AlertDialog.Builder builder;
    AlertDialog dialog;
    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) {

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

                if(text.trim().length()>0 && text != null) {

                    builder.create().getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);

                }
                    else {
                        builder.create().getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
                }

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {

            }

        });

        dialog = builder.create();
        dialog.show();
        dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);

    }
}

当我执行应用程序并且editext为空时,正面按钮是不可选择的(正确)但当我尝试插入文本崩溃时出现此错误

01-01 17:04:07.839: E/AndroidRuntime(20624): FATAL EXCEPTION: main
01-01 17:04:07.839: E/AndroidRuntime(20624): Process: com.package.name, PID: 20624
01-01 17:04:07.839: E/AndroidRuntime(20624): java.lang.NullPointerException
01-01 17:04:07.839: E/AndroidRuntime(20624):    at com.package.name.Example$1.onTextChanged(Example.java:42)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.widget.TextView.sendOnTextChanged(TextView.java:7408)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.widget.TextView.handleTextChanged(TextView.java:7467)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9183)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:675)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:437)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:333)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.os.Handler.dispatchMessage(Handler.java:102)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.os.Looper.loop(Looper.java:136)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at android.app.ActivityThread.main(ActivityThread.java:5081)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at java.lang.reflect.Method.invokeNative(Native Method)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at java.lang.reflect.Method.invoke(Method.java:515)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-01 17:04:07.839: E/AndroidRuntime(20624):    at dalvik.system.NativeStart.main(Native Method)

第42行是builder.create()。getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);

3 个答案:

答案 0 :(得分:0)

观看此示例,我认为它会对您有所帮助。新年快乐! main.xml中

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/buttonPrompt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Prompt Dialog" />

<EditText
    android:id="@+id/editTextResult"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

</EditText>

prompts.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Type Your Message : "
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/editTextDialogUserInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <requestFocus />

</EditText>

public class MainActivity extends Activity {

final Context context = this;
private Button button;
private EditText result;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // components from main.xml
    button = (Button) findViewById(R.id.buttonPrompt);
    result = (EditText) findViewById(R.id.editTextResult);

    // add button listener
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            // get prompts.xml view
            LayoutInflater li = LayoutInflater.from(context);
            View promptsView = li.inflate(R.layout.prompts, null);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);

            // set prompts.xml to alertdialog builder
            alertDialogBuilder.setView(promptsView);

            final EditText userInput = (EditText) promptsView
                    .findViewById(R.id.editTextDialogUserInput);

            // set dialog message
            alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                    // get user input and set it to result
                    // edit text
                    result.setText(userInput.getText());
                    }
                  })
                .setNegativeButton("Cancel",
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                    dialog.cancel();
                    }
                  });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();

        }
    });
}
}

答案 1 :(得分:0)

如果您更换

builder.create().getButton(Dialog.POSITIVE_BUTTON)

dialog.getButton(Dialog.POSITIVE_BUTTON)

它应该可以解决你的问题。您正尝试在未显示的新对话框上设置启用/禁用按钮,因此按钮不存在

答案 2 :(得分:0)

因为你在做一些基本的错误,我会根据你的需要用工作代码更新你的代码:

public class Example extends AlertDialog {

    AlertDialog.Builder builder;
    AlertDialog dialog;
    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) {

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

                if(text.trim().length()>0 && text != null) {

                    dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);

                }
                    else {
                    dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
                }

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {

            }

        });

        dialog = builder.create();
        dialog.show();
        dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);

    }
}

希望这能解决你的问题。

欢呼声,

哈马德谢赫