java - 如何在用户输入时在 EditText 中添加主题标签

标签 java android kotlin

我在 editext 中创建 hashTag 时遇到问题。

以下是我的要求

1.每当用户开始输入时,它都会以哈希开头。如果用户输入“G”,那么整个单词将类似于“#g”。

2.输入单词后,用户输入空格并输入“T”,然后输入“#t”。

我尝试过使用文本更改监听器,但它对我不起作用。

我尝试过使用textwatcher:

tt = object:TextWatcher {
            override fun afterTextChanged(s: Editable) {
                edtTags.setSelection(s.length)
            }
            override fun beforeTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {}
            override  fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
                edtTags.removeTextChangedListener(tt)
                edtTags.setText(edtTags.getText().toString().replace(" ", " #"))
                edtTags.addTextChangedListener(tt)
            }
        }
        edtTags.addTextChangedListener(tt)

谢谢!

最佳答案

这对我有用,在类似的情况下:

        var isSelfChanging = false
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (!isSelfChanging) {
                    isSelfChanging = true

                    val formattedText = ("#" + s.toString()) // adds a hashtag in start
                        .replaceFirst("##", "#") // removes initial hashtag if needed
                        .replace(" #", " ") // removes all hashtag at the begging of words
                        .replace(Regex(" (\\S)"), " #$1") // re-adds the hashtags at the begging of words
                        .toLowerCase(Locale.getDefault()) // forces lowercase
                    if (s.toString() != formattedText) {
                        s?.replace(0, s.length, formattedText, 0, formattedText.length)
                    }
                    isSelfChanging = false
                }
            }

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

它并不完美,特别是当用户尝试编辑文本中间时,但大多数自动完成功能在这种情况下都不能很好地工作

关于java - 如何在用户输入时在 EditText 中添加主题标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61615591/

相关文章:

java - 获取响应正文作为字符

android - 调用 AsyncTask.get() 时未显示 ProgressDialog

android - 添加 RealmList<Int> (Kotlin) 时出现 RealmMigrationNeededException

kotlin - 使用 Kotlin WHEN 子句进行 <、<=、>=、> 比较

android - 以编程方式更改 clans fab 菜单方向

java - Camel管道如何与jms端点一起工作

java - 从 JSF 项目根文件夹中读取 html 文件

java - 如何更改导航栏颜色?

android - 在益智游戏中,一个可绘制的图像裁剪成九个 block 如何在android中实现

android - 如何在 MVVM 架构的 RecyclerView 适配器中观察 LiveData?