在android中关闭对话框时是否需要删除TextWatcher?

问题描述

我想在我的对话框中收听 TextView 文本更改,所以 我正在使用如下所示的 TextWatcher:

 final View layout = activity.getLayoutInflater().inflate(R.layout.popup_history,container,false);
            final Dialog dialog = new Dialog(context,R.style.full_screen_dialog);

            dialog.setContentView(layout);
            final Window window = dialog.getwindow();
            WindowManager.LayoutParams layoutParams;
            if (window != null) {

              

                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT);
                layoutParams = window.getAttributes();
                if (layoutParams != null) {
                    layoutParams.windowAnimations = R.style.ChooserStyle;
                    layoutParams.gravity= Gravity.BottOM;
                    window.setAttributes(layoutParams);
                }
            }


           


            TextView searchHistoryTV = layout.findViewById(R.id.searchHistoryTV);


            searchHistoryTV.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s,int start,int count,int after) {

                }

                @Override
                public void onTextChanged(CharSequence s,int before,int count) {
                    CharSequence editable = searchHistoryTV.getText();
                    //thereafter use this CharSequence

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });


            dialog.setCanceledOnTouchOutside(true);
            dialog.setCancelable(true);
            dialog.show();

是否需要在对话框关闭删除 TextWatcher,即在 dialog.setondismissListener() 中?或者如果我不删除它会怎样?

解决方法

无需特别删除任何 FirebaseFirestore rootRef = FirebaseFirestore.getInstance(); CollectionReference usersRef = rootRef.collection("users"); Query queryUsersByName = usersRef.whereEqualTo("name","John"); queryUsersByName.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (DocumentSnapshot document : task.getResult()) { if (document.exists()) { Log.d("TAG","name already exists"); } else { //Do what you need to do } } } else { Log.d("TAG","Error getting documents: ",task.getException()); } } }); ,一旦 listeners 解除,它里面的所有子 dialog 实例无论如何都会被销毁。因此,即使您不移除 view,也不会发生任何事情,因为它附加到 TextListener 也会被销毁 EditText