在Kotlin上的RecyclerView中保存EditText内容

时间:2019-07-06 22:15:50

标签: android kotlin android-recyclerview

类似于Saving EditText content in RecyclerView,我实现了一对EditText的实现,以填充RecyclerView的每一行。但是,即使在调用updatePosition函数之后,TextWatcher中的位置变量始终返回0。

即使在第3个位置填充editText之后,两个Watchers上的afterTextChanged()上的Lod.d也始终显示该位置为0。

我看到在onBindViewHolder函数执行期间updatePosition从0到areaimportadas.size,但是对于onTextChanged却没有。

class importItemsAdapter(val areaImportadas:MutableList,val inclinaLida:MutableList,val desvLido:MutableList):RecyclerView.Adapter(){

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
   val layoutInflater = LayoutInflater.from(parent.context)
   val cellForRow = layoutInflater.inflate(R.layout.import_items,parent,false)
    return CustomViewHolder(cellForRow)
}

override fun getItemCount(): Int {
   return areasImportadas.size
}

override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
    holder.itemView.importNum.text = (position+1).toString()
    holder.itemView.importArea.text = areasImportadas[position]
    Watcher1().updatePosition(holder.adapterPosition)
    Watcher2().updatePosition(holder.adapterPosition)
    holder.itemView.importInclina.addTextChangedListener(Watcher1())
    holder.itemView.importDesv.addTextChangedListener(Watcher2())
}

class CustomViewHolder(view: View): RecyclerView.ViewHolder(view)

private inner class Watcher1 : TextWatcher {
    var position = 0

    fun updatePosition(positionExt: Int) {
        this.position = positionExt
        Log.d("Registro", this.position.toString())
    }

    override fun afterTextChanged(arg0: Editable) {
        inclinaLida[position]= arg0.toString()
        Log.d("Registro", "Inclinação $position: ${inclinaLida[position]}")
    }

    override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}

    override fun onTextChanged(s: CharSequence, a: Int, b: Int, c: Int) {

    }
}

private inner class Watcher2 : TextWatcher {
    var position = 0

    fun updatePosition(positionExt: Int) {
        position = positionExt
        Log.d("Registro", position.toString())
    }
    override fun afterTextChanged(arg0: Editable) {
        Log.d("Registro", "Desvio ${position}: ${desvLido[position]}")
    }

    override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {
    }

    override fun onTextChanged(s: CharSequence, a: Int, b: Int, c: Int) {
        desvLido[position]=s.toString()
    }

}

}

我需要能够将每个EditText内容存储在两个列表(desvLido和inclinaLida)的适当位置下

1 个答案:

答案 0 :(得分:0)

缺少一个实例:

override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {

    holder.itemView.importNum.text = (position+1).toString()
    holder.itemView.importArea.text = areasImportadas[position]
    val watcher1 = Watcher1()
    watcher1.updatePosition(holder.adapterPosition)
    holder.itemView.importInclina.addTextChangedListener(watcher1)
}

现在位置返回正确的值。