skip to Main Content

I have a layout xml where the following line occurs:

<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/rootLayout"
...

and in Kotline I have the following line to refer to this element:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

    val rootLayout = findViewById(R.id.rootLayout)
    ...

The findViewById function is underlined in red telling
‘Not enough information to infer type variable T’

Why is this happening. Clearly the type should be ‘ConstraintLayout’

Why the error?

2

Answers


  1. Try with this:

    val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
    
    Login or Signup to reply.
  2. Hovering over the red underline should give you the following note:

    Note: In most cases — depending on compiler support — the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.

    So you’ve faced the unconstrained case, the reason for which is explained here and can be fixed by specifying the generic type:

    val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search