2012-09-11 51 views
1

我尝试向我的Android应用中的EditText对象(用户可以编辑的文本区域)添加事件句柄以控制用户可以编辑的内容或不。 说我有这样的文字在我的EditText:Android,EditText事件,防止文本的某些部分可以被删除/更改

* Hello 
    * World 
    * On You... 

我会附上一个控制器,允许用户只能编辑HelloWorldOn You,如果用户尝试编辑或删除*和第一*之后的空间将停止编辑。

在Java SE上,我可以使用Document.remove(int, int)获取事件,而用户尝试删除或替换部分文本,然后停止编辑。

是否有类似的API用于android EditText?

我一直在使用TextWatcher尝试,但据我所知,这是不是要帮我, 我知道方法public void onTextChanged(CharSequence s, int start, int before, int count)给一些笔记关于它的文字删除用户但这似乎并不可靠。 这让我无法停止编辑使用这件事。

编辑: 我可以使用Spanner防止编辑文本的一部分吗?作为只读扳手?

有人知道解决我的问题的好方法吗?

+0

你说**“但这看起来不可靠”**请解释原因。 –

+0

是不是真的不可靠,但这给了我洞字而不是输入字符,如果我在电话中输入“你好”,这将首先给我“H”,“他”,“Hel”,“地狱” “这对我来说不是我想要的。我现在试着将它翻译成我将要做的,我已经发现'InputFilter'用于编辑/拒绝编辑,但在这里也有同样的问题。 –

回答

0

我想我已经最终找到了工作中的困境,但必须更深入地尝试以确定这是否存在一些错误或错误。

public abstract class TextListener implements InputFilter { 

    public abstract CharSequence removeStr(CharSequence removeChars, int startPos); 

    public abstract CharSequence insertStr(CharSequence newChars, int startPos); 

    public abstract CharSequence updateStr(CharSequence oldChars, int startPos, CharSequence newChars); 

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
     CharSequence returnStr = source; 
     String curStr = dest.subSequence(dstart, dend).toString(); 
     String newStr = source.toString(); 
     int length = end - start; 
     int dlength = dend - dstart; 
     if (dlength > 0 && length == 0) { 
      // Case: Remove chars, Simple 
      returnStr = TextListener.this.removeStr(dest.subSequence(dstart, dend), dstart); 
     } else if (length > 0 && dlength == 0) { 
      // Case: Insert chars, Simple 
      returnStr = TextListener.this.insertStr(source.subSequence(start, end), dstart); 
     } else if (curStr.length() > newStr.length()) { 
      // Case: Remove string or replace 
      if (curStr.startsWith(newStr)) { 
       // Case: Insert chars, by append 
       returnStr = TextUtils.concat(curStr.subSequence(0, newStr.length()), TextListener.this.removeStr(curStr.subSequence(newStr.length(), curStr.length()), dstart + curStr.length())); 
      } else { 
       // Case Replace chars. 
       returnStr = TextListener.this.updateStr(curStr, dstart, newStr); 
      } 
     } else if (curStr.length() < newStr.length()) { 
      // Case: Append String or rrepace. 
      if (newStr.startsWith(curStr)) { 
       // Addend, Insert 
       returnStr = TextUtils.concat(curStr, TextListener.this.insertStr(newStr.subSequence(curStr.length(), newStr.length()), dstart + curStr.length())); 
      } else { 
       returnStr = TextListener.this.updateStr(curStr, dstart, newStr); 
      } 
     } else { 
      // No update os str... 
     } 

     // If the return value is same as the source values, return the source value. 
     return TextUtils.equals(source, returnStr) ? source : returnStr; 
    } 
} 

从这个代码,我可以轻松防止通过查找文本的选择部分编辑是在我尝试编辑的文本。