Home > Net >  Android Studio unable to infer type of element define in xml
Android Studio unable to infer type of element define in xml

Time:10-20

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?

CodePudding user response:

Try with this:

val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)

CodePudding user response:

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 type:

val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
  • Related