[英]How to detect when user's done entering the value to EditText in RecyclerView?
我有一個包含 EditTexts 的 recyclerview。 只有在用戶完成在任何編輯文本中輸入金額后,我如何才能獲得每個編輯文本的值,以便我可以更新總金額。
我想要實現的是添加 edittexts 的值並將其發送到 Activity。 在活動中,我有“繼續”按鈕(我將在其中對總量執行一些驗證)和總量 TextView(使用偵聽器從 recyclerview 適配器檢索)。
我嘗試使用setOnEditorActionListener
但如果用戶單擊后退按鈕而不是按回車鍵,這將無濟於事。
此外,我嘗試使用焦點更改偵聽器,但問題是即使在頁面外部單擊,EditText 也永遠不會失去焦點。
當然,TextWatcher 不是一個理想的解決方案,因為它在 OnBindViewHolder 中可能非常昂貴。
我需要確保每當用戶單擊“繼續”按鈕時,總金額都會在之前更新。
最好的方法是添加兩個通信(通過接口):
Activity
和Adapter
之間的 FIRST
Adapter
和單個ViewHolder
之間的 SECOND
添加此類通信后,您可以“實時”計算總和。
創建第一個interface
,例如:
interface AdapterContentChanged {
fun valuesChanged()
}
並在您的 Activity 中實現它或創建新變量(作為匿名類)。
在創建適配器時傳遞您的活動(或上述接口的實例),例如:
private val ownAdapter = OwnAdapter(
items, // elements inside list
this // interface implementation
)
創建第二個interface
,例如:
interface OwnViewHolderTextChanged {
fun onTextChanged(position: Int, newValue: Int)
}
並在您的適配器中實現它或創建新變量(匿名類) - 與步驟 #1中相同。
在綁定 viewHolder 時傳遞您的適配器(或變量)和position
(項目的),例如:
override fun onBindViewHolder(holder: OwnViewHolder, position: Int) {
val number = list[position]
holder.bind(number, position, this)
}
在bind()
方法中(來自上面的示例),將新的TextWatcher
添加到您的EditText
。
在afterTextChanged()
方法(來自TextWatcher
)中,從接口調用方法並傳遞新值。 例如:
fun bind(
// TODO - add here more information which you need,
position: Int,
listener: OwnViewHolderTextChanged
) {
itemView.edit_text.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
// Get EditText content
val newValue = getNumber()
// Call method from interface
listener.onTextChanged(position = position, newValue = newValue)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// Not used
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// Not used
}
})
}
要從EditText
計算值,您可以使用如下代碼:
private fun getNumber(): Int =
try {
itemView.edit_text.text.toString().toInt()
} catch (e: Exception) {
0
}
在方法中更改文本時,您必須:
更新列表內容
通知適配器“某些內容已更改”
例如:
override fun onTextChanged(position: Int, newValue: Int) {
list[position] = newValue
listener.valuesChanged()
}
當發生變化時(Activty 會知道),您可以計算新的總和:
override fun valuesChanged() {
val sum: Int = ownAdapter.getCurrentSum()
text_view.text = "Sum: $sum"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.