简体   繁体   中英

Android Kotlin - viewBinding Type mismatch: inferred type is DrawerLayout but ConstraintLayout was expected

I'm trying to get viewBinding to work.

This is the code:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view: ConstraintLayout = binding.root
    setContentView(view)
}

I manually declared the type ConstraintLayout because it's what I'm using for that activity called AskProfileImage :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#303030"
    tools:context=".AskProfileImage">

    <ImageView
        android:id="@+id/imageView97545"
        android:layout_width="108dp"
        android:layout_height="64dp"
        android:layout_marginTop="8dp"
        android:background="#00FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/logo2" />

But I'm getting the error

Type mismatch: inferred type is DrawerLayout but ConstraintLayout was expected

on

binding.root

how to fix this?

viewBinding creates a class for each activity. So in my case for this activity it's:

ActivityAskProfileImageBinding

So the correct code is:

private lateinit var binding: ActivityAskProfileImageBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityAskProfileImageBinding.inflate(layoutInflater)
    setContentView(binding.root)
}

Since viewBinding is probably broadly used now, I don't understand why the hell nobody could answer that and why google docs are as always useless

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM