我一直在尝试使用EditText获取特定行为。 这是我启用旋转的简单活动。当我输入一些文字时, <{1}}方法被触发。
当我旋转手机时,不应触发此方法,因为onTextChanged
中保存的文本已在onInstanceState
方法中设置为EditText
。
然而,当我将手机旋转回原来的方向时,方法再次触发!请参阅本文末尾的logcat。
这是来自新创建的Android Studio项目的复制和粘贴代码。
onCreate
UPD:
默认情况下,Android会在每个方向更改时保留所有editText字段中的文本(具有唯一ID)。这就是我旋转手机时触发onTextChanged的原因。为了避免这种情况,我在onCreate之后放置了onTextChanged监听器,因此它会在文本设置为EditText后监听事件。但它没有按预期工作(logcat)。查看最后一个链接以获取更多信息
logcat的:
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.search_query);
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("MainActivity", "charSequence:" + charSequence);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
相关: TextWatcher called even if text is set before adding the watcher
答案 0 :(得分:0)
看看this电影,特别是在:
您可以注意到第一个
EditText
(带ID)中的文字会保留 方向改变后没有变化,以及onTextChanged()
方法 还会调用TextChangedListener
来更新TextView
。另一方面,第二个
EditText
(未分配ID)将会 方向改变时清除为空。
无论如何,您可以在this的athor回答中取消onTextChanged()
:
...你可以通过以下方式解决这个问题:
- 在设置文本之前删除TextWatcher,然后将其添加回来。
- 或者在设置文本之前设置一个布尔标志,告诉TextWatcher忽略它。
E.g。
boolean ignoreNextTextChange = true; ((EditText) findViewById(R.id.MyEditText)).setText("Hello");
在您的
中TextWatcher
:new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { /* If the flag is set to ignore the next text change, reset the flag, and return without doing anything. */ if (ignoreNextTextChange){ ignoreNextTextChange = false; return; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } });
答案 1 :(得分:0)
如果已将输入的文本保存在savedInstanceState中,则只需检查是否已保存变量,并根据该条件从中获取值并将其设置为edittext。无论多少次调用一些方法。 :D问题解决了。
答案 2 :(得分:0)
所以,问题出在设备上。其他设备(如Nexus 5X)未显示任何问题,代码按预期工作。