androidkotlinlayoutsetcontentview

Kotlin: "Unresolved reference: layout" in setContentView()


I'm new to Android development with Kotlin. I'm trying to set the content view of my activity, but I'm getting an Unresolved reference: layout error in Android Studio on this line:

setContentView(R.layout.activity_main)

My activity_main.xml file exists in the res/layout folder and the project builds without errors. I've tried cleaning and rebuilding the project, invalidating caches and restarting Android Studio, but the error persists.

Here's the relevant code from my MainActivity.kt:

package com.example.mylayouttest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // Error occurs here
    }
}

And a snippet from my activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

 </LinearLayout>

Could there be an issue with my project setup, imports, or something else I'm overlooking?


Solution

  • Unresolved reference: layout occurs when layout resources cannot be loaded properly.

    For example, you can reproduce this error by creating a new project in Android Studio and deleting the res/layout folder. This suggests that your res/layout directory is not being recognized correctly. The code you've attached looks correct, so the issue might be elsewhere.

    I suggest trying to create a completely new project by going to File > New > New Project > Empty Views Activity and see if the same problem occurs.

    If the issue persists in the new project, there might be a problem with your development environment. If the new project works fine, then the issue is likely in your current project's code or configuration.