Android - onTextChanged() called on when phone orientation is changed

大城市里の小女人 提交于 2019-12-21 04:35:10

问题


I tried to implement search using EditText. whenever a text is typed in the EditText request is sent with the typed text in onTextChanged() method. When I change the orientation of the phone with the results displyed, onTextChanged() method is called again with same text. How can I avoid redundant call to onTextChanged() method on orientation change.

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

回答1:


I've got this problem just. So I moved addTextChangedListener to the post method of EditText in the 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) {
                    }
                });
            }
        });
}



回答2:


You need to override onConfigurationChanged method to get callback whenever orientation is getting changed.

@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 in manifest

android:configChanges= "orientation"

Now based on the callback you can do whatever you wanted to do.



来源:https://stackoverflow.com/questions/27792635/android-ontextchanged-called-on-when-phone-orientation-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!