Jas*_*son 5 android textwatcher android-edittext
我需要检测EditText中的文本更改.我已经尝试过TextWatcher,但是它没有按照我期望的方式工作.采用onTextChanged方法:
public void onTextChanged( CharSequence s, int start, int before, int count )
假设我在EditText中已经有了"John"文本.如果按另一个键,"e",s将是"Johne",start将是0,before将是4,并且count将是5.我希望这种方法工作的方式将是EditText之前的内容与什么之间的区别它即将成为.
所以我希望:
s = "Johne"
start = 4 // inserting character at index = 4
before = 0 // adding a character, so there was nothing there before
count = 1 // inserting one character
Run Code Online (Sandbox Code Playgroud)
我需要能够在每次按下按键时检测个别更改.因此,如果我有文本"John",我需要知道索引4处添加了"e".如果我退格"e",我需要知道"e"已从索引4中删除.如果我将光标放在"J"之后"和退格,我需要知道"J"已从索引0中删除.如果我把"G"放在"J"中,我想知道"G"在索引0处替换为"J".
我怎样才能做到这一点?我想不出一个可靠的方法来做到这一点.
Sam*_*udd 11
使用textwatcher并自己做diff.将前一个文本存储在观察者中,然后将之前的文本与您在onTextChanged上获得的任何序列进行比较.由于onTextChanged在每个字符后被触发,因此您知道您之前的文本和给定的文本最多只有一个字母,这样可以很容易地找出添加或删除的字母.即:
new TextWatcher(){
String previousText = theEditText.getText();
@Override
onTextChanged(CharSequence s, int start, int before, int count){
compare(s, previousText); //compare and do whatever you need to do
previousText = s;
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10542 次 |
| 最近记录: |