简体   繁体   English

如何显示带有edittext onTextChanged的AlertDialog

[英]How to show AlertDialog with edittext onTextChanged

I have an activity with several EditTexts . 我有一个带有几个EditTextsactivity If the user clicks ' Cancel ' button and nothing has changed in these EditTexts then the app should go to the previous activity but if something has changed in these EditTexts then I want the user to see the AlertDialog : 如果用户单击“ Cancel ”按钮,但这些EditTexts没有任何更改,则应用程序应转到上一个活动,但是如果这些EditTexts有更改,则希望用户看到AlertDialog

Save changes you made?

NO       YES

I have set up a TextWatcher for these EditTexts like: 我已经为这些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);

And my AlertDialog for the Cancel button - which is appearing regardless of whether any EditTexts have changed or not, but I just want it to appear only if changes are made in the EditTexts , otherwise there should be no AlerDialog and current activity should go back to previous activity - goes like: 我的AlertDialog for Cancel按钮-无论是否有任何EditTexts更改都出现,但是我只希望仅在EditTexts中进行更改时才显示它,否则应该没有AlerDialog并且当前活动应返回到先前的活动-如下所示:

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();
            }
        }
    };

I have searched the internet for tutorials or posts with phrases like 'TextWatcher' and 'AlertDialog' but I've not found something that will help me acheive what I am trying to do. 我已经在互联网上搜索了带有“ TextWatcher”和“ AlertDialog”之类的短语的教程或帖子,但是我没有找到可以帮助我实现自己想做的事情的东西。

Try add alertDialog like below, you can put dialog inside onAfterChange method: 尝试添加如下所示的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(); } }; 

Create a boolean variable to track textChange 创建一个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);

And change you cancel button click event to this 并将您的取消按钮单击事件更改为此

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();
                }

            }

        });


    }

You simply use boolean variable like so 您只需像这样使用布尔变量

  • declare check variable in class properties 在类属性中声明检查变量

    boolean check ; 布尔检查;

  • set the value of this variable in onTextChange() to true in the TextWatcher 这个变量的值设置onTextChange()trueTextWatcher

  • change cancelButton() to this 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 "); } } }); } 

You can do something like this 你可以做这样的事情

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

In cancel button onClick method just try this :- 在取消按钮的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

   }

Just check the text in all the edittexts , if any one of them is not empty , show the dialog.. !! 只需check the text所有edittexts check the text ,如果其中任何一个都不为空,则显示对话框。

No need to add textChangeListener for the above problem !! 无需为上述问题添加textChangeListener

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM