i am unable to import anything from activity_main.xml to MainActivity.kt by its id such as textview or button

Viewed 5952

I saw I lot of videos says that the Kotlin can recognize the buttons (views) automatically in MainActivity.kt I try this but it doesn't work for me in android studio 4.1 when I'm using the usual code with :

var button_name = findViewById(R.id.buttonName)

it works fine but when I'm using the code directly like this :

buttonName.setonclicklistiner{}

the IDE doesn't recognize the button

PS : this the imports in the mainactivity

import android.os.Bundle

import android.view.View

import androidx.appcompat.app.AppCompatActivity

What can i do for access my button or textView automatically in MainActivity.kt

7 Answers

In build.gradle(module) make sure plugins contains following 3 plugins -

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

Open build_gradle(:app) and make sure you have these two lines in dependencies block

dependencies {

    apply plugin : "kotlin-android"

    apply plugin : "kotlin-android-extensions"
    ...
}

Please make sure you have these 2 lines at the top of your gradle file

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

If your xml name is "activity_main.xml" then import like below:

import kotlinx.android.synthetic.main.activity_main.*

You must import the xml file into your kotlin folder by insert

import com.example.yourappsname.databinding.ActivityMainPageBinding

Change "ActivityMainPageBinding" to your XML file name. Incase your XML file name is "name_folder", your import should be

import com.example.yourappsname.databinding.NameFolderBinding

Also do not forget to change "yourappsname" to your real application name.

weird solution but it works example you have a button called btnfirst

import kotlinx.android.synthetic.main.activity_main.btnfirst as btnfirst1

btnfirst1.setOnClickListener {
        if (rs.moveToFirst()) {
            edid.setText(rs.getInt(0))
            edname.setText(rs.getText(1))
            edmarks.setText(rs.getText(2))
        }
    }

None of the solutions provided above worked for me . Only the weird solution that i provided removed errors.

weird solution but it works example you have a button called btnfirst

import kotlinx.android.synthetic.main.activity_main.btnfirst as btnfirst1

btnfirst1.setOnClickListener {
    if (rs.moveToFirst()) {
        edid.setText(rs.getString(0))
        edname.setText(rs.getString(1))
        edmarks.setText(rs.getString(2))
    }
}
Related