如何显示带有 edittext onTextChanged 的​​ AlertDialog

How to show AlertDialog with edittext onTextChanged

我有一个 activity 和几个 EditTexts。如果用户单击“Cancel”按钮并且这些 EditTexts 中没有任何变化,那么应用程序应该转到之前的 activity 但如果这些 EditTexts 中有任何变化,那么我希望用户看到 AlertDialog:

Save changes you made?

NO       YES

我已经为这些EditTexts设置了一个TextWatcher,例如:

  //let's set up a textwatcher so if the state of any of the edittexts has changed.
    //if it has changed and user clicks 'CANCEL', we'll ask first, '
    //You've made changes here. Sure you want to cancel?'
    TextWatcher edittw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

            Toast.makeText(EditContact.this, "change detected", Toast.LENGTH_SHORT).show();

        }
    };

    categoryname.addTextChangedListener(edittw);
    namename.addTextChangedListener(edittw);
    phonename.addTextChangedListener(edittw);
    addressname.addTextChangedListener(edittw);
    commentname.addTextChangedListener(edittw);

还有我的 AlertDialog 用于 Cancel 按钮 - 无论任何 EditTexts 是否已更改,它都会出现,但我只希望它仅在进行更改时出现在 EditTexts 中,否则不应该有 AlerDialog,当前的 activity 应该回到之前的 activity - 就像:

private void cancelButton() {

        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                //add a dialogue box
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setMessage("Save changes you made?").setPositiveButton("Yes", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();

            }

        });


    }

    //Are you sure you want to cancel? dialogue
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    //Yes button clicked

                    pDialog = new ProgressDialog(EditContact.this);
                    // Showing progress dialog for the review being saved
                    pDialog.setMessage("Saving...");
                    pDialog.show();

                    //post the review_id in the current activity to EditContact.php and

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, EditContact_URL,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //hide the dialogue saying 'Saving...' when page is saved
                                    pDialog.dismiss();

                                    Toast.makeText(EditContact.this, response, Toast.LENGTH_LONG).show();
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Toast.makeText(EditContact.this, "problem here", Toast.LENGTH_LONG).show();

                                }

                            }) {

                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<String, String>();
                            //we are posting review_id into our EditContact.php file,
                            //the second value, review_id,
                            // is the value we get from Android.
                            // When we see this in our php,  $_POST["review_id"],
                            //put in the value from Android
                            params.put("review_id", review_id);
                            return params;
                        }


                    };


                    AppController.getInstance().addToRequestQueue(stringRequest);

                    //when cancelled, back to the PopulistoListView class

                    Intent j = new Intent(EditContact.this,PopulistoListView.class);

                    startActivity(j);


                    break;

                case DialogInterface.BUTTON_NEGATIVE:

                    //close the activity
                    finish();
            }
        }
    };

我在互联网上搜索了包含 'TextWatcher' 和 'AlertDialog' 等短语的教程或帖子,但我没有找到可以帮助我实现我想要做的事情的东西。

尝试像下面这样添加 alertDialog,你可以将对话框放在 onAfterChange 方法中:

TextWatcher edittw = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {

                Toast.makeText(EditContact.this, "change detected", Toast.LENGTH_SHORT).show();

                AlertDialog.Builder builder;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    builder = new AlertDialog.Builder(getApplicationContext(), android.R.style.Theme_Material_Dialog_Alert);
                } else {
                    builder = new AlertDialog.Builder(getApplicationContext());
                }
                builder.setTitle("Delete entry")
                        .setMessage("Are you sure you want to delete this entry?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //You want yes
                            }
                        })
                        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //You want no
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        };

你可以这样做

//onCancel Clicked
if(somethingChanged)//compare old values with new values
   showDialog();
else
   onBackPressed();

创建一个 boolean 变量来跟踪 textChange

boolean isDirty;
TextWatcher edittw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

            Toast.makeText(EditContact.this, "change detected", Toast.LENGTH_SHORT).show();
            isDirty = true;

        }
    };

    categoryname.addTextChangedListener(edittw);
    namename.addTextChangedListener(edittw);
    phonename.addTextChangedListener(edittw);
    addressname.addTextChangedListener(edittw);
    commentname.addTextChangedListener(edittw);

并将取消按钮点击事件改成这个

private void cancelButton() {

        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                if(isDirty) {
                    //add a dialogue box
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setMessage("Save changes you made?").setPositiveButton("Yes", dialogClickListener)
                            .setNegativeButton("No", dialogClickListener).show();
                }
                else {
                    // this will finish the current activity and the last activity will be popped from the stack. 
                    finish();
                }

            }

        });


    }

在取消按钮的 onClick 方法中试试这个:-

 @Override
 onClick(View v) {

   if(!(categoryname.getText().toString().isEmpty() && namename.getText().toString().isEmpty() && phonename.getText().toString().isEmpty() && addressname.getText().toString().isEmpty() && commentname.getText().toString().isEmpty())) {

   // show your dialog
   }
   else {

     // normal cancel

   }

所有edittexts中只有check the text,如果其中任何一个不为空,则显示对话框..!!

No need to add textChangeListener for the above problem !!

你只需像这样使用布尔变量

  • 在 class 属性中声明检查变量

    布尔检查;

  • onTextChange()中的这个变量的值设置为TextWatcher

  • 中的true
  • cancelButton()改成这个

    private void cancelButton() {
    
    cancel.setOnClickListener(new View.OnClickListener() {
    
        @Override
        public void onClick(View view) {
            if(changed){
    
            AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
    
            builder.setMessage("Save changes you made?").setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();
    
            }else {
    
                Log.v(TAG,"nothing changed ");
    
            }
        }
    });
    
    }