I cannot call an "id" of the "Mainactivity.kt" file inside the "activity_main.xml" file

Asked

Viewed 52 times

-1

Hello. I’m starting the program. I’m using Android Studio with the Kotlin language.

I’m trying to call an "id", which is inside the file "activity_main.xml" in the file "Mainactivity.kt", I’m not getting it. I tried to import the "activity_main.xml" file, but also I can’t. Someone has been there, knows how to solve ?


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)

    principalTXT.setOnClickListemer {
        
    }

}

<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" tools:context=". Mainactivity">

<TextView
    android:id="@+id/principalTXT"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constrainaintlayout.widget.Constraintlayout>

1 answer

0

The simplest way to get your View reference is:

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

        val principalTXT = findViewById<TextView>(R.id.principalTXT)
        principalTXT.setOnClickListemer {
            // implemente sua ação aqui
        }
    }
}

There is a better way to access these references called "View Binding", which I recommend instead of using findViewById. Take a look at documentation if you want to see more details about this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.