簡體   English   中英

帶有貨幣格式的 addTextChangedListener 上的 EditText cursor position

[英]EditText cursor position on addTextChangedListener with currency format

更改 EditText 內容后,是否可以將 cursor 放在選定的 position 上? 我已經制作了這些代碼:

binding.editText1.addTextChangedListener(object : TextWatcher {

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

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

override fun afterTextChanged(s: Editable?) {
         val stringText = s.toString()

         if (stringText != current) {
              binding.editText1.removeTextChangedListener(this)

              val localeid = Locale("in", "ID")
              val format1 = NumberFormat.getInstance(localeid) as DecimalFormat
              format1.applyPattern("#,###.##")

              val doublecont : Double
              val cont = binding.editText1.text.toString().trim()
              doublecont = if (cont.isNotEmpty()) {
                        
            
           cont.replace("\\.","").replace(",","").replace(".","").toDouble()
                    } else {
                        0.0
                    }

              binding.editText1.setText(format1.format(doublecont))                 
             binding.editText1.setSelection(binding.editText1.text!!.length)
              binding.editText1.addTextChangedListener(this)
         } else {
              binding.editText1.setText("0")
         }
     }
})

我仍然對setSelection()感到困惑,我從上面的代碼中得到的結果是cursor將 go 到 EditText 字符的末尾。 我想要的是當我將cursor移動到 position X 並在其上鍵入任何數字時, cursor將留在最新的數字/字符后面。 有什么想法嗎?

您正在使用setSelection(binding.editText1.text.!.length)將 cursor position 顯式設置為EditText的末尾。 請記住,這發生在_after_TextChanged回調中,因此新文本已經添加。

您需要使用其他方法之一來處理此問題,該方法會告訴您 position 發生更改的位置( start ),以及有多少字符正在替換現有的多少( count表示不同的東西,具體取決於它是哪種方法)。 通過這種方式,您可以確定 cursor 需要放置的位置。

我不記得您是否可以在這些方法中執行setSelection或者稍后將其覆蓋,但您可以做的一件事是在TextWatcher object 中設置一個臨時值:

object : TextWatcher {
    var selectionPosition: Int? = null

然后你可以在前面的回調中設置它,並在afterTextChanged中使用它。 基本上找出cursor需要go的位置,然后再設置position。 完成后清除它 - 但如果你總是設置它,它不需要可以為空,因為它總是在afterTextChanged觸發之前設置為適當的值。

順便說一句,暫時刪除TextWatcher的好技巧,我總是添加一個更新標志來忽略更改。 下次我一定要用那個!

暫無
暫無

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

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