想法
最好的方法是添加两个通信(通过接口):
添加此类通信后,您可以“实时”计算总和。
解决方案
步骤 #1
创建 FIRST interface,例如:
interface AdapterContentChanged {
fun valuesChanged()
}
并在您的 Activity 中实现它或创建新变量(作为匿名类)。
步骤 #2
在创建适配器时传递您的活动(或上述接口的实例),例如:
private val ownAdapter = OwnAdapter(
items, // elements inside list
this // interface implementation
)
第三步
创建 SECOND 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)
}
第 5 步
在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
}
第 6 步
当文本在方法内部发生变化时,你必须:
例如:
override fun onTextChanged(position: Int, newValue: Int) {
list[position] = newValue
listener.valuesChanged()
}
第 7 步
当发生变化时(Activty 会知道这一点),你可以计算新的总和:
override fun valuesChanged() {
val sum: Int = ownAdapter.getCurrentSum()
text_view.text = "Sum: $sum"
}
演示