输入double space以替换multiautocompletetextview中的逗号

时间:2016-11-10 05:56:34

标签: java android multiautocompletetextview android-textwatcher

我想在multiautocompletetextview中从键盘输入双倍空格时添加逗号。我在谷歌搜索很多东西。但无法实现我的目标。我想用逗号替换用户输入的双倍空格。

很明显,我必须在addtextwatcher listener中的ontextChange()或OnAfterTextChanged()中编写一些逻辑。但是我在添加2个空格后没有得到事件。

我从list中选择单词时已经使用过逗号标记器。但是当用户使用键盘输入双倍空格时我想添加逗号。

提前致谢

2 个答案:

答案 0 :(得分:1)

试试这样,我还没试过这段代码

boolean userPressedKey = false ;
int spaceCount = 0;


yourEditText.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        userPressedKey = false ;
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        userPressedKey = true;
    }); 


public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (userPressedKey) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
            spaceCount ++;
            if(spaceCount == 2){
                 //append comma to the edittext here
                 Toast.makeText(MainActivity.this, "White space is clicked twice", Toast.LENGTH_LONG).show();
            }

            return true;
        }else{
            spaceCount=0;
        }
    }
    super.onKeyDown(keyCode, event);
}

答案 1 :(得分:1)

我可以为您提供的最简单的解决方案是使用String.replace(),这是一个小代码片段来帮助您

 @Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    edt.addTextChangedListener(textWatcher);
}

您要在TextWatcher

上设置的EditText
TextWatcher textWatcher = 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) {
        edt.removeTextChangedListener(textWatcher);
        String text = edt.getText().toString();
        text = text.replace("  ", ",");
        edt.setText(text);
        edt.setSelection(text.length());
        edt.addTextChangedListener(textWatcher);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};

enter image description here