2012-02-27 94 views
5

我需要檢測EditText中的文本更改。我已經嘗試了TextWatcher,但它不能以我期望的方式工作。就拿onTextChanged方法:檢測EditText中的更改(TextWatcher無效)

public void onTextChanged(CharSequence s, int start, int before, int count)

說我有文字「約翰」在已經在EditText上。如果按另一個鍵「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 

我需要能夠每一個鍵被按下的時間來檢測各個更改。所以如果我有文本「約翰」,我需要知道在索引4處添加了「e」。如果我退格「e」,我需要知道從索引4中刪除了「e」。如果將光標放在「J 「並且退格時,我需要知道從指數0中刪除了」J「。如果我在其中加入了」J「的」G「,我想知道指數爲0的」G「代替了」J「。

我可以做到這一點嗎?我想不出一個可靠的方法來做到這一點。

+0

嘗試onKeyListener的EditText上 – 2012-02-27 03:32:42

+0

怎麼樣從剪貼板粘貼? – 2012-02-27 16:14:32

+0

我遇到的另一個問題是說我選擇了一個文本範圍。在任何TextWatcher方法中,getSelectionStart和End始終是相同的索引,無論我是否選擇了文本。 – 2012-02-27 16:44:28

回答

9

使用一個textwatcher自己做差異。將先前的文本存儲在觀察器中,然後將以前的文本與您在TextTextChanged上獲得的任何序列進行比較。由於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; 
    } 

    ... 
} 
+0

這是一個我曾經考慮過的建議,當然也是可行的,但我希望有一個簡單的「你走吧!」方法,它可能不存在。你的方法唯一的問題是,文本可以相差超過1個字母(選擇範圍,從剪貼板粘貼)。 – 2012-02-27 16:14:02

+1

確實如此,但在這一點上,索引沒有什麼意義(例如,如果您在當前文本之前粘貼一個詞,會發生什麼情況?),即使如此,您仍然可以自己做差異。我不認爲有什麼內置的解決方案可以幫助你做什麼。 – 2012-02-27 22:44:02

+0

夠公平的。我最終做了你所說的,基本上實現了我自己的TextWatcher,並傳遞了我期望的值。這不是100%的傻瓜證明,但它非常接近。 – 2012-02-28 17:01:51

0

每次更改文本時都需要存儲和更新以前的CharSequence。您可以通過執行TextWatcher來實現。

例子:

final CharSequence[] previousText = {""}; 
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) 
    { 
     if(i1 > 0) 
     { 
      System.out.println("Removed Chars Positions & Text:"); 
      for(int index = 0; index < i1; index++) 
      { 
       System.out.print((i + index) + " : " + previousText[0].charAt(i + index)+", "); 
      } 
     } 
     if(i2 > 0) 
     { 
      System.out.println("Inserted Chars Positions & Text:"); 
      for(int index = 0; index < i2; index++) 
      { 
       System.out.print((index + i) + " : " + charSequence.charAt(i + index)+", "); 
      } 
      System.out.print("\n"); 
     } 
     previousText[0] = charSequence.toString();//update reference 
    } 

    @Override public void afterTextChanged(Editable editable) 
    { 
    } 
});