问题描述
||
我有一个
EditText
视图,该视图由我的代码中的and1ѭ编辑,并由用户通过(软/硬)键盘进行编辑,如果可能,还可以通过语音输入进行编辑。我想用普通用户输入以外的其他方式来处理代码输入:如果发生用户输入,则将触发内部事件。但是我不知道如何区分两者。以前-在仿真器上开发时-我使用onKeyDown()
方法捕获用户输入。但是,在真实设备上进行测试时,我发现ѭ2并不是从软键盘输入触发的。另外,尽管我认为这是次要的缺陷,但语音输入无法被识别。因此,该解决方案对我来说是没有选择的。
另一方面,有onTextChanged()
方法,但这是由setText()
和键盘输入触发的。那么,如何区分这两种方法,或者仅由用户输入来调用哪种方法,而在使用setText()
时不能区分,那么我可以覆盖它吗?
解决方法
最后,我实现了一个ѭ7(这个问题,特别是实现示例的答案),从而解决了该问题,该方法有多种方法可以从软键盘获取输入。我用
EditText.onCreateInputConnection()
方法返回InputConnectionWrapper
。对于硬键盘,我使用EditText.onPreIme()
。所有这些方法均被覆盖,并通过我的框架路由其输入,该框架处理文本输入并相应地更新View。这意味着,在所有这些被覆盖的方法中(ѭ11除外),都不会调用super方法,因为我自己更新了View。这样可以防止我的数据模型和视图之间的不一致。
, 我相信android不允许您在程序化和手动输入的文本之间进行区分。唯一的解决方法是使用一些sla来指示代码是何时设置测试的,因为您总是知道何时调用setText()。
, 您可以使用标志来区分。
((EditText) rootView.findViewById(R.id.editText1)).addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence,int i,int i2,int i3) {
}
public void onTextChanged(CharSequence charSequence,int i3) {
}
public void afterTextChanged(Editable editable) {
update(true);
}
});
private boolean updating = false;
private void update(boolean multiply) {
if(updating){
return;
}
updating = true;
EditText editText1 = (EditText) getView().findViewById(R.id.editText1);
editText1.setText(\"XXX\");
updating = false;
}
, 这里已经有很多不错的解决方法!我想添加对我有用的内容,以便为将来可能遇到此问题的任何人提供选择。
我使用了TextWatcher,只是在编辑EditText时仅依靠检查当前具有焦点的元素。请注意,如果在您的应用程序中,用户必须在输入文本之前将焦点赋予EditText(例如,通过单击它),并且您确定当您在代码中使用setText
。
像这样
yourEditText.addTextChangedListener(
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s,int start,int count,int after) {
}
@Override
public void onTextChanged(CharSequence s,int before,int count) {
if (yourEditText.hasFocus) {
//this is a user input
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
);
, 旋转设备时遇到此问题。我的editText在对话框中。这是我的解决方法:
editText.addTextChangedListener(
new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String newValue = s.toString();
String oldValue = (String) editText.getTag();
if (newValue.length() > 0) {
editText.setTag(newValue);
}
boolean itReallyChanged = oldValue != null && !newValue.equals(oldValue) && !newValue.isEmpty();
if (itReallyChanged) {
// Pretty sure the user genuinely changed this value,// not the device rotation
}
}
}
);