[英]Android - onTextChanged() called on when phone orientation is changed
I tried to implement search using EditText
. 我尝试使用EditText
实现搜索。 whenever a text is typed in the EditText
request is sent with the typed text in onTextChanged()
method. 只要在EditText
中输入文本, onTextChanged()
在onTextChanged()
方法中使用键入的文本发送请求。 When I change the orientation of the phone with the results displyed, onTextChanged()
method is called again with same text. 当我使用显示的结果更改手机的方向时,将使用相同的文本再次调用onTextChanged()
方法。 How can I avoid redundant call to onTextChanged()
method on orientation change. 如何避免在方向更改时对onTextChanged()
方法进行冗余调用。
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);
}
}
I've got this problem just. 我刚才遇到了这个问题。 So I moved addTextChangedListener to the post method of EditText in the onCreateView: 所以我将addTextChangedListener移动到onCreateView中的EditText的post方法:
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) {
}
});
}
});
}
You need to override onConfigurationChanged method to get callback whenever orientation is getting changed. 您需要覆盖onConfigurationChanged方法,以便在方向发生变化时获得回调。
@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. 现在基于回调你可以做任何你想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.