检测的EditText变化(TextWatcher无效) [英] Detect changes in EditText (TextWatcher ineffective)

查看:237
本文介绍了检测的EditText变化(TextWatcher无效)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检测一个EditText文本更改。我试过TextWatcher,但它不会在某种程度上我希望它的工作。就拿onTextChanged方式:

I need to detect text changes in an EditText. I've tried TextWatcher, but it doesn't work in a way I would expect it to. Take the onTextChanged method:

公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数)

说我有文字约翰在已经在的EditText。如果preSS另一个关键,E,取值将强尼启动为0, 之前将是4,和计数将5.我希望这种方法的工作将是差异的方法之间什么的EditText previously是,什么是即将成为

Say I have the text "John" in already in the EditText. If press another key, "e", s will be "Johne", start will be 0, before will be 4, and count will be 5. The way I would expect this method to work would be the difference between what the EditText previously was, and what it's about to become.

所以,我希望:

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

我需要能够每一次关键是pressed检测各个更改。所以,如果我有文字约翰,我需要知道的e指数在4加入如果我退格键E,我需要知道的e指数从4辗转如果我把光标之后Ĵ 和Backspace,我需要知道J从索引0被删除。如果我把一个G,其中J是的,我想知道索引0 G替换为J。

I need to be able to detect individual changes every time a key is pressed. So if I have text "John", I need to know "e" was added at index 4. If I backspace "e", I need to know "e" was removed from index 4. If I put the cursor after "J" and backspace, I need to know "J" was removed from index 0. If I put a "G" where "J" was, I want to know "G" replaced "J" at index 0.

我怎样才能做到这一点?我想不出一个可靠的方法来做到这一点。

How can I achieve this? I can't think of a reliable way to do this.

推荐答案

使用一个textwatcher并做diff的自己。存储观察家里面的previous文本,然后比较previous文本到任何顺序你onTextChanged。由于onTextChanged是每个字符后被炒了,你知道你的previous文本和给定的文本将至多一个字母,这应该使简单弄清楚添加或移除其中字母不同。即:

Use a textwatcher and do the diff yourself. store the previous text inside the watcher, and then compare the previous text to whatever sequence you get onTextChanged. Since onTextChanged is fired after every character, you know your previous text and the given text will differ by at most one letter, which should make it simple to figure out what letter was added or removed where. ie:

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

    ...
}

这篇关于检测的EditText变化(TextWatcher无效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆