2011-02-07 55 views
9

我必须做一些明显的事情,但我无法弄清楚它是什么。我只是试图插入一个字符到一个可编辑:无法插入到可编辑

@Override 
public void afterTextChanged(Editable s) { 
    Log.d(TAG, "inserting space at " + location); 
    s.insert(location, " "); 
    Log.d(TAG, "new word: '" + s + "'"); 
} 

但s永远不会改变。字符串'''够长,因为我打印它,它看起来不错。如果我调用Editable.clear(),它将被清除,并且我可以用Editable.replace()替换多个字符。想法?

回答

25

我发现这个问题;我将inputType设置为“number”,因此静静地添加空间失败。

+0

有什么办法可以添加一个空格到inputType为“number”的EditText? –

+0

是的,请参阅下面的答案;它涉及到暂时清除输入过滤器。 – BeccaP

+1

您可以使用'android:inputType =“phone”'来代替'number'。它显示数字,但旁边有小写字母。我会说普通用户不会意识到差异。 – Syex

1

尝试:

Editable s = getLatestEditable(); 
Log.d(TAG, "inserting space at " + location); 
s.insert(location, " "); 
Log.d(TAG, "new word: '" + s + "'"); 
+0

对不起没有,getEditable()是我自己的方法。其实这是从TextWatcher.afterTextChanged回调(可编辑) –

9

要使用输入过滤器编辑可编辑内容,只需保存当前过滤器,清除它们,编辑文本,然后恢复过滤器。

这里是为我工作的一些示例代码:

@Override 
public void afterTextChanged(Editable s) { 
    InputFilter[] filters = s.getFilters(); // save filters 
    s.setFilters(new InputFilter[] {});  // clear filters 
    s.insert(location, " ");    // edit text 
    s.setFilters(filters);     // restore filters 
} 
+0

这对我有用!比哈克接受的答案要好得多。 – CrashproofCode