简体   繁体   English

在新课程中与Kotlin一起使用recyclerView

[英]recyclerView with Kotlin in new class

have created a recyclerView with Kotlin on mainActivity. 在mainActivity上使用Kotlin创建了一个recyclerView。

it works just fine. 它工作正常。

I would like now to transfer my code to a new class Call that class from MainActivity and activate the recyclerView that way. 我现在想将代码转移到新类中,从MainActivity调用该类并以这种方式激活recyclerView。

Called that class at mainActivity, but apperantly that is not enough… 在mainActivity上调用了该类,但是显然这还不够……

var newClass: NewClass = NewClass()

How do I call a class with a recyclerView or how to activate it ? 如何使用recyclerView调用类或如何激活它?

Added the call for newClass. 添加了对newClass的调用。 Would like to remove all of these lines. 想要删除所有这些行。

Thank you 谢谢

This is my code at onCreate: 这是我在onCreate上的代码:

enter code here

var newClass: NewClass = NewClass()


rowsList = ArrayList<RowFromModel>()
layoutManager = LinearLayoutManager(this)
adapter = RowListAdapter(rowsList!!, this)

rowsListRv.layoutManager = layoutManager
rowsListRv.adapter = adapter

//load data
var model = TableViewModel()

var dataFromModel: ArrayList<String> = model.getData()
for (i in 0..dataFromModel.size - 1) {
    val rowFromModel = RowFromModel()
    rowFromModel.row = dataFromModel.get(i)
    rowsList!!.add(rowFromModel)
}

adapter!!.notifyDataSetChanged()
enter code here

The problem is that NewClass need some way to know the recyclerView and the Context (or Activity) to work on, so they should be passed to the class. 问题在于, NewClass需要某种方式来了解recyclerViewContext (或Activity)才能进行工作,因此应将它们传递给类。 You can do so by doing the following 您可以执行以下操作

class NewClass (val recyclerView: RecyclerView, val context: Context) {

    val rowsList = ArrayList<RowFromModel>() 
    val layoutManager = LinearLayoutManager(context) 
    val adapter = RowListAdapter(rowsList, context)

    // load data
    var model = TableViewModel()

    var dataFromModel: ArrayList<String> = model.data 
    val rowFromModel = RowFromModel()

    init {
        // this will be called after the constructor is called
        recyclerView.layoutManager = layoutManager 
        recyclerView.adapter = adapter 

        for (i in 0..dataFromModel.size - 1) {
            val rowFromModel = RowFromModel()
            rowFromModel.row = dataFromModel[i]
            rowsList.add(rowFromModel)
        }

        adapter.notifyDataSetChanged()
    }
}

and then in your MainActivity 's onCreate() , you can do the following 然后在MainActivityonCreate() ,可以执行以下操作

var newClass: NewClass = NewClass(rowsListRv, this)

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM