Reputation: 75
have created a recyclerView with Kotlin on mainActivity.
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.
Called that class at mainActivity, but apperantly that is not enough…
var newClass: NewClass = NewClass()
How do I call a class with a recyclerView
or how to activate it ?
Added the call for newClass. Would like to remove all of these lines.
Thank you
This is my code at 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
Upvotes: 0
Views: 348
Reputation: 2128
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. 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
var newClass: NewClass = NewClass(rowsListRv, this)
Hope this helps!
Upvotes: 1