【问题标题】:How to detect when user's done entering the value to EditText in RecyclerView?如何检测用户何时完成在 RecyclerView 中向 EditText 输入值?
【发布时间】:2020-05-15 21:54:59
【问题描述】:

我有一个包含 EditTexts 的 recyclerview。只有在用户完成在任何编辑文本中输入金额后,我才能获取每个编辑文本的值,以便我可以更新总金额。

我想要实现的是添加编辑文本的值并将其发送到活动。在 Activity 中,我有 Proceed 按钮(我将在其中对总金额执行一些验证)和总金额 TextView(使用侦听器从 recyclerview 适配器检索)。

我尝试使用setOnEditorActionListener,但如果用户单击后退按钮而不是按回车键,这将无济于事。

另外,我尝试使用焦点更改侦听器,但问题是即使在页面外部单击时 EditText 也永远不会失去焦点。

当然,TextWatcher 并不是一个理想的解决方案,因为它在 OnBindViewHolder 中可能非常昂贵。

我需要确保每当用户点击继续按钮时,总金额会在之前更新。

【问题讨论】:

  • 我的解决方案有效吗? :)
  • 是的,Boken,您的解决方案正在运行。谢谢

标签: java android kotlin android-recyclerview


【解决方案1】:

想法

最好的方法是添加两个通信(通过接口):

  • ActivityAdapter 之间的第一个

  • Adapter 和单个 ViewHolder 之间的第二个

添加此类通信后,您可以“实时”计算总和。

解决方案

步骤 #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"
}

演示

【讨论】:

  • 贴切!很详细。
猜你喜欢
  • 1970-01-01
  • 2020-05-21
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 2020-12-21
  • 1970-01-01
相关资源
最近更新 更多