[SOLVED] Not able to access elements with kotlin in android studio

Issue

I am new to android studio and wanted to make a pretty basic app. The problem is after creating an xml file and giving it id as btnApply, i tried to print something when it gets clicked. I think the code is correct as I have been following a youtube tutorial, but something else like my settings is not allowing me to access the xml file elements. Any fixes??

package com.example.applicationone

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

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

        btnApply.setOnClickListner{
            Log.d("MainActivity", "Button Clicked")
        }
    }

Solution

To use btnApply, you first have to declare it. Instead use findViewById<Button>(R.id.btnApply) Also, if you want to learn android, google’s course might be a good start.
Use the code below if btnApply is your button’s id

findViewById<Button>(R.id.btnApply).setOnClickListner{
    Log.d("MainActivity", "Button Clicked")
}

Answered By – Vaishnav Kanhirathingal

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.