Android - onTextChanged () called when the orientation of the phone changes

I tried to implement search using EditText

. whenever text is entered into a request EditText

, it is sent with the entered text in the method onTextChanged()

. When I change the orientation of the phone with the canceled results, the method onTextChanged()

is called again with the same text. How can I avoid redundant method call onTextChanged()

when orientation changes.

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

    final String enteredKeyword = s.toString();


    if(isFragmentVisible && !enteredKeyword.equals("")) {

    searchTimer.cancel();
    searchTimer = new Timer();
    TimerTask searchTask = new TimerTask() {
    @Override
    public void run() {
          searchUser(enteredKeyword);
    }
};
searchTimer.schedule(searchTask, 1500);
Log.i("", enteredKeyword);
}
}

      

+3


source to share


2 answers


I have this problem. So I moved addTextChangedListener to the post EditText method in onCreateView:



public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ...

    EditText mSearchQuery = findViewById(R.id.search_query);
    mSearchQuery.post(new Runnable() {
            @Override
            public void run() {
                mSearchQuery.addTextChangedListener(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) {
                        //Some stuff
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
            }
        });
}

      

+6


source


You need to override the onConfigurationChanged method to get a callback when the orientation changes.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // landscape
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        // portrait
    }
}

      

Add below line to manifest



android:configChanges= "orientation"

      

Now, based on the callback, you can do whatever you want.

0


source







All Articles