Home » Android » android – How can i set layoutmanager to RecycleView using kotlin

android – How can i set layoutmanager to RecycleView using kotlin

Posted by: admin June 15, 2020 Leave a comment

Questions:

How can i set layoutmanager to RecycleView using kotlin as java code below:

mRecyclerView.setLayoutManager(mLinearLayoutManager);
How to&Answers:

Following two lines sets orientation to vertical

mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL ,false)

OR

mRecyclerView.layoutManager = LinearLayoutManager(this)
mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL ,false)

sets horizontal orientation

To set grid layout,

mRecyclerView.layoutManager = GridLayoutManager(this, spanCount)

Answer:

You can use

recyclerView.layoutManager = LinearLayoutManager(context) // default orientation is vertical

// if you want horizontal recyclerview
// recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)

Answer:

You can do like this

val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
recyclerview!!.layoutManager = linearLayoutManager
recyclerview!!.isNestedScrollingEnabled = true
recyclerview!!.setHasFixedSize(true)

Answer:

Simply write this to set LayoutManager

 // Define this globally
 lateinit var recyclerView: RecyclerView

 // Initialize this after `activity` or `fragment` is created
 recyclerView = findViewById(R.id.recyclerView) as RecyclerView

 recyclerView.setHasFixedSize(true)
 recyclerView.layoutManager = LinearLayoutManager(activity!!) as RecyclerView.LayoutManager

Answer:

I had same issue, reason was I had initialize recyclerView as

var recyclerView = findViewById<View>(R.id.recycleView)

Make sure you initialize as below

var recyclerView = findViewById<View>(R.id.recycleView) as RecyclerView

Answer:

Apply plugin in your app build

 apply plugin: 'kotlin-android-extensions'

For my case view id of RecyclerView is my_recycler_view.

In your java file write –

my_recycler_view.layoutManager = LinearLayoutManager(context)

By default LinearLayoutManager(context) will set vertical orientation, update it as per need.

Answer:

You can set using this code:

binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.layoutManager = LinearLayoutManager(this ,LinearLayoutManager.VERTICAL ,false)
binding.recyclerView.adapter = customAdapter(this ,getList())

Answer:

private var mRecyclerView: RecyclerView? = null

mRecyclerView?.layoutManager = LinearLayoutManager(activity)

Answer:

You can try using below solution

val mRecyclerView= v.findViewById<RecyclerView>(R.id.rec) //id RecyclerView    
mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false)

Answer:

recyclerView.layoutManager = LinearLayoutManager(context)

or

recyclerView.layoutManager = GridLayoutManager(context, spanCount)