当项目添加到 RecyclerView 时,RecyclerView 中的 EditText 值会发生变化

Mar*_*eer 2 android android-edittext kotlin android-recyclerview

我有一个 RecyclerView,其中包含带有 EditText 字段的视图列表。

我希望能够更改 EditTexts 中的值并更新我的数据集。我似乎正在完成此任务,但是当我向列表中添加新项目时,EditText 中的值会混淆。

我找不到为什么会发生这种情况。有什么想法吗?

主要活动

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var viewAdapter: RecyclerView.Adapter<*>
    private lateinit var viewManager: RecyclerView.LayoutManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myDataSet = ArrayList<Person>()
        myDataSet.add(Person("Tommy"))
        myDataSet.add(Person("John"))
        myDataSet.add(Person("Suzie"))
        myDataSet.add(Person("Leslie"))

        viewManager = LinearLayoutManager(this)
        viewAdapter = PersonAdapter(myDataSet)

        recyclerView = findViewById<RecyclerView>(R.id.rvPersons).apply {
            setHasFixedSize(true)

            layoutManager = viewManager
            adapter = viewAdapter
        }

        val button = findViewById<Button>(R.id.myButton)

        button.setOnClickListener {
            myDataSet.add(Person("new person"))
            myDataSet.forEach {person ->
                Log.i("my-tag", person.name)
            }
            rvPersons.adapter?.notifyDataSetChanged()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

人员适配器

class PersonAdapter(private val myDataSet: ArrayList<Person>) :
    RecyclerView.Adapter<PersonAdapter.MyViewHolder>() {

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val editText: EditText = view.my_edittext
        var textView: TextView = view.my_textView
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_person, parent, false)
        )
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.editText.setText(myDataSet[position].name)
        holder.editText.doAfterTextChanged { text ->
            if (!text.isNullOrBlank()) {
                myDataSet[position].name = text.toString()
            }
        }
        holder.textView.text = myDataSet[position].name
    }

    override fun getItemCount(): Int = myDataSet.size
}
Run Code Online (Sandbox Code Playgroud)

小智 7

对于回收者视图回收问题:- 添加此

@Override
public int getItemViewType(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}
Run Code Online (Sandbox Code Playgroud)