簡體   English   中英

如何在用戶輸入時在 EditText 中添加主題標簽

[英]How to prepend a hashtag in EditText on user's typing

我在 editext 中創建 hashTag 時遇到問題。

以下是我的要求

1.當用戶啟動類型時,它以 hash 開頭。 如果用戶鍵入“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
            }
        })
    }

它並不完美,特別是如果用戶嘗試編輯文本的中間部分,但大多數自動完成在這種情況下都不能很好地工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM