eugene_prg
eugene_prg

Reputation: 1168

Address elements by ID instead of findViewById

I've just started learning android development and Android Studio is a complete mess after xcode ;)

I have an element with ID "mybutton" and i want to use it in my kotlin code. So, to avoid using findViewById i want to use it's id (which is "mybutton"). But when i enter mybutton in the code IDE doesn't understand it and doesn't ask me to import anything.

I've just seem in online course that it should ask if i want to use "mybutton" from activity_main but in my case it does not. So i don't know how to address the elements by id ;)

Please help

package com.example.helloworld

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Button
import android.widget.Toast

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // get reference to button
            val btn_click_me = findViewById(R.id.mybutton) as Button
            var myTextView = findViewById(R.id.textView) as TextView
            var timesClicked = 0
    // set on-click listener
            mybutton.setOnClickListener { // <<------ here, mybutton is red and i can't use it
                Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
                myTextView.text = "Hey it's me again, "
                timesClicked += 1
            }
    
        }

Am i doing something wrong? May be i should activate something in IDE?;)

Upvotes: 0

Views: 580

Answers (1)

eugene_prg
eugene_prg

Reputation: 1168

i found that i should add the following line

import kotlinx.android.synthetic.main.content_main.*

but to add it i had to add also these 2 lines

  1. In project-level build.gradle

    buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version" } }

and apply the kotlin-android-extensions plugin:

  1. In module-level build.gradle

apply plugin: 'kotlin-android-extensions'

Is there something wrong with me? It's my first "hello world" on android.. it is normal i should invent a hyperloop to use ID-reference?

Upvotes: 1

Related Questions