0
 private fun initRecyclerView(){
       studentRecyclerView.layoutManager=LinearLayoutManager(this)

        layoutManager.reverseLayout=true
        layoutManager.stackFromEnd=true

        adapter = StudentRecyclerViewAdapter{
            selectedItem:Student -> listitemclicked(selectedItem)
        }
        studentRecyclerView.adapter=adapter
        displayStudentList()
    }

I want to reverse the recycler view, but whenever I use layoutManager.reverseLayout and layoutManager.stackFromEnd these lines throw an error.

I don't know what to do.

Rubydesic
  • 3,386
  • 12
  • 27
  • 2
    Could you start by editing your post to include what error you have? – xihtyM Mar 20 '23 at 14:34
  • Also, this is just guesswork, but shouldn't `layoutManager` be `studentRecyclerView.layoutManager`? – xihtyM Mar 20 '23 at 14:41
  • this reverselayout and stackFromEnd could be used with the variable name but i do not know what is variable name in this beacuse i do not declare any variable of layout manager above –  Mar 20 '23 at 14:44
  • Try [this](https://stackoverflow.com/questions/46168245/recyclerview-reverse-order). – xihtyM Mar 20 '23 at 14:57

1 Answers1

0

setReverseLayout and setStackFromEnd are both functions on the LinearLayoutManager class, not the base LayoutManager one. So you have to make sure the variable you're referencing has a LinearLayoutManager type (or cast it):

// implicitly setting the type to the class you're constructing
val layoutManager = LinearLayoutManager(this)

// or you can just specify it explicitly
val layoutManager: LinearLayoutManager = LinearLayoutManager(this)

// now you can configure that object, and set it on the RecyclerView
layoutManager.setReverseLayout(true)
studentRecyclerView.layoutManager = layoutManager

studentRecyclerView.layoutManager's type is just the base LayoutManager (so you can provide different implementations of a layout manager), so if you read that property you'll just get a LayoutManager. If you wanted to treat it as a LinearLayoutManager specifically (and access the functions and properties on that type), you'd have to cast it:

studentRecyclerView.layoutManager = LinearLayoutManager(this)
...
(studentRecyclerView.layoutManager as LinearLayoutManager).setReverseLayout(true)

This is messy though, and it's usually better to just hold your own reference with the correct type - no need to complicate things, especially during a simple setup block!


And because it's Kotlin, set* functions can be written as a property (e.g. layoutManager.reverseLayout = true) and the IDE will offer to change the function version to the property version, if appropriate. Same thing though, just a different way of writing it.

cactustictacs
  • 17,935
  • 2
  • 14
  • 25