在用户键入内容时,如何将一个注释替换为另一个注释(用“-”替换“空格”

时间:2019-05-02 04:34:42

标签: android android-edittext textwatcher

我正在使用类似于SO的标签系统,而不是强迫用户在键盘上找到破折号,我希望将空间自动转换为破折号。

我正在尝试使用此textWatcher来实现它,但该应用程序不允许我键入空格键(有点闪烁但什么也没发生。

        imageTagsInput.addTextChangedListener(object : TextWatcher {

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                imageTagsInput.removeTextChangedListener(this)
                imageTagsInput.setText(imageTagsInput.text.toString().replace(" ","-"))
                imageTagsInput.addTextChangedListener(this)
                imageTagsInput.setSelection(imageTagsInput.length())


            }

            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

        })

这是EditText的xml:                android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-  "

1 个答案:

答案 0 :(得分:1)

在afterTextChanged中添加类似的内容

  String result = s.toString().replaceAll(" ", "-");
    if (!s.toString().equals(result)) {
         ed.setText(result);
         ed.setSelection(result.length());
         // alert the user
    }

有关更多信息,请参见此answer