skip to Main Content

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")
        }
    }

2

Answers


  1. 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")
    }
    
    Login or Signup to reply.
  2. If you’ve been following some tutorial, it’s probably using the deprecated Kotlin synthetics library that automagically looks up views when you refer to them without declaring them. Either move to View Binding (which is basically the same thing except you access your IDs on a Binding object you initialise) or look them up the basic way with findViewById like in Vaishnav’s answer

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search