gpt4 book ai didi

android - 使用 Adapter 将数据绑定(bind)到 RecyclerView 时出现问题。没有看到模型类

转载 作者:行者123 更新时间:2023-12-02 13:31:33 35 4
gpt4 key购买 nike

基本上我想使用适配器将数据绑定(bind)到我的 RecyclerView 但似乎我在定义适配器的 Activity 中看不到我的数据列表

listItems.adapter = FormRecyclerAdapter(this, TestFileManager.testForms) // testForms highlighted(unresloved reference)

看起来它应该可以工作,但可能存在一些误解或其他我无法解决的问题。

这是我的课

MainActivity.kt
class MainActivity: AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)
setContentView(activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.title = "Forms creator"


listItems.layoutManager = LinearLayoutManager(this)
listItems.adapter = FormRecyclerAdapter(this, TestFileManager.testForms) <- here is where the problem occurs
}

}

测试文件管理器.kt
class TestFileManager {

private val testForms = ArrayList<TestForm>()

init {
initializeForms()
}

fun initializeForms() {
var testForm = TestForm("Form 1", "Created Jun 1 2020")
testForms.set(0, testForm)

testForm = TestForm("Form 2", "Created 5 Jan 2019")
testForms.set(1, testForm)

testForm = TestForm("Form 3", "Created 3 March 2020")
testForms.set(2, testForm)
}
}

测试表格.kt
class TestForm( var name: String, var description: String)

FormRecyclerAdapter.kt
class FormRecyclerAdapter(private val context: Context, private val forms: List<TestForm>) :
RecyclerView.Adapter<FormRecyclerAdapter.ViewHolder>() {

private val layoutInflater = LayoutInflater.from(context)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = layoutInflater.inflate(R.layout.item_form_list, parent, false)
return ViewHolder(itemView)
}

override fun getItemCount() = forms.size

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val form = forms[position]
holder.textTitle?.text = form.name
holder.textDescription?.text = form.description
}

class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
val textTitle = itemView?.findViewById<TextView?>(R.id.textTitle)
val textDescription = itemView?.findViewById<TextView?>(R.id.textDescription)
}
}

可能是一些愚蠢的问题或误解,但我自己很难找到它。

最佳答案

试试这个 :

fun initializeForms() {
var testForm = TestForm("Form 1", "Created Jun 1 2020")
testForms.add(testForm)

testForm = TestForm("Form 2", "Created 5 Jan 2019")
testForms.add(testForm)

testForm = TestForm("Form 3", "Created 3 March 2020")
testForms.add(testForm)
}

ArrayList.set(int index, E element) 将此列表中指定位置的元素替换为指定元素。

您的列表为空。

调用:TestFileManager().testForms

关于android - 使用 Adapter 将数据绑定(bind)到 RecyclerView 时出现问题。没有看到模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61202298/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com