Home > other >  Classifier 'LayoutManager' does not have a companion object, and thus must be initialized
Classifier 'LayoutManager' does not have a companion object, and thus must be initialized

Time:01-06

Here is my code package com.example.newsshare

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        RecyclerView.LayoutManager = LinearLayoutManager(this)
    }

}

i am new to kotlin and android development if anyone know how to solve this please help

i looked for solution which says it should be in abstract class but i dont know how to do it

CodePudding user response:

First you need a reference to an instance of RecyclerView (an actual RecyclerView object). Here's one way you can do it (assuming you have a RecyclerView in layout_activity_main with an ID called recycler):

val recyclerView = findViewById<RecyclerView>(R.id.recycler)

Now you can mess with its layoutManager property, and set a value on it:

// using the RecyclerView instance we just declared and assigned
recyclerView.layoutManager = LinearLayoutManager(this)

Note the case - it's layoutManager not LayoutManager. Case matters in Kotlin (and Java), and by convention properties and variables and functions start with lowercase letters (camelCase specifically). Class names start with uppercase letters (Pascal case). So when you do this:

RecyclerView.LayoutManager

you're really referring to the LayoutManager class nested in the RecyclerView class, not the layoutManager property of an actual RecyclerView object.

CodePudding user response:

You are not referencing the recycler view you (probably) have created within your activity / fragment, that's why you are not able to set a layout manager.

You need to create a reference to your recycler view either using viewBinding (or databinding) or findViewById(R.id.YOUR_RECYLCER_VIEW_ID)

you may find a full implementation here

  • Related