Textwatcher giving Stackoverflow error

前端 未结 2 1082
心在旅途
心在旅途 2021-01-23 12:15

i am making a length converter which uses TextWatcher. the shortened code is

 v1.addTextChangedListener(new TextWatcher() {

         @Override
            publi         


        
2条回答
  •  悲哀的现实
    2021-01-23 12:31

    Do not do setText inside onTextChanged(),it is causing recursion.

    You can try the following: Set a boolean variable when you do setText from inside the onTextChange(). This boolean variable will help to identify that onTextChange was called because text was change programmatically and not by the user,thus avoiding recursion

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                          if(isTextChangedByUser){
                              //calculate and set different values only when user has changed       values
                               editext.setText("programmatically setting the text,change the flag")
                               isTextChangedByUser=false;
                           }else{
                               //to avoid recursion
                                return;
                           }
            }
    

    Second time when onTextChanged is called it will simply return since isTextChangeByUser flag is false.In this manner we will avoid recursion.

    Alternatively,to make the implementation more simple you can put a "calculate" button next to each editext.You will only start calculation when the user presses this button and not when text changes.

提交回复
热议问题