skip to Main Content

I’m a Kotlin newbie, I’m trying to call a button BTN_test but I can’t

MainActivity.kt

package com.example.testapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.widget.Toast

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

        var btn = BTN_test
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="#575757"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/BTN_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/st_btn1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="146dp"
        android:layout_height="54dp"
        android:layout_alignParentTop="true"
        android:layout_marginStart="150dp"
        android:layout_marginTop="100dp"
        android:layout_marginEnd="150dp"
        android:text="@string/st_textView"
        android:textSize="15sp"
        tools:ignore="SmallSp" />

</RelativeLayout>

I tried to add this to the gradle file

    id 'kotlin-android'
    id 'kotlin-android-extensions'

build.gradle(test app)

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

task clean(type: Delete) {
    delete rootProject.buildDir
} 

But this error appeared

Build file 'C:UserssuhaibAndroidStudioProjectstestappbuild.gradle' line: 3

Plugin [id: 'com.android.application'] was not found in any of the following sources:

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'com.android.application'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (plugin dependency must include a version number for this source)
    at org.gradle.plugin.use.internal.DefaultPluginRequestApplicator.resolveToFoundResult(DefaultPluginRequestApplicator.java:222)
    at org.gradle.plugin.use.internal.DefaultPluginRequestApplicator.lambda$resolvePluginRequests$4(DefaultPluginRequestApplicator.java:148)...

This error also appears

Gradle sync failed: Plugin [id: 'com.android.application'] was not found in any of the following sources:
               - Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
               - Plugin Repositories (plugin dependency must include a version number for this source) (2 s 524 ms)

About Android Studio

Android Studio Bumblebee | 2021.1.1 Patch 3
Build #AI-211.7628.21.2111.8309675, built on March 16, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 4
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: org.jetbrains.kotlin (211-1.6.21-release-334-AS7442.40)

note

I managed to solve the problem, I will leave this question for others to benefit

the solution
I put the plugins in the wrong place
I should have written it on the build.gradle(:app) instead of the build.gradle(test app)

So that the build.gradle(:app) is like this

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

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.testapp"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

thank you ^_^

6

Answers


  1. When working with Views in Android you cannot directly reference an element defined in an xml layout file. The Activity class has the method findViewById() which you should use to do this as below.

    val btn = findViewById(R.id.BTN_test)

    Incidentally. The fact that you don’t know this already suggests that you have missed out several fundamental steps in your Android learning. I highly recommend you go back and start from the beginning as it will save you a lot of headache in the long term.
    The official training is a good place to start and will teach you better ways to reference views than findViewById() as well as lots of other essential info. Good luck

    https://developer.android.com/courses/android-basics-kotlin/unit-1

    Login or Signup to reply.
  2. Button button = (Button)findViewById(R.id.BTN_test);

    Login or Signup to reply.
  3. In order to work with Views within your MainActivity.kt, you must reference not only the view itself, but also what the button could do. You did create a button within the UI design, however to make the button do something after a click. You do this:

    You type this within the onCreate() in MainActivity.kt

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            var btn = findViewById<Button>(R.id.BTN_test)
            btn.setOnClickListener {
                //Do something after the button is clicked
            }
        }
    
    }
    
    Login or Signup to reply.
  4. I recommend you to use the binding structure, it is more innovative and saves you a lot of code.

    build gradle(module)

    buildFeatures {
            viewBinding true
            dataBinding true
        }
    

    MainActivity

    class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityHomeBinding.inflate(layoutInflater)
            setContentView(binding.root)
    
            binding.apply{
             val btn=BTNTest
           
         }
    
       }
    
    }
    
    Login or Signup to reply.
  5. You must set the button equal to the instance of the button view in the XML file:

    var button = findViewById<Button>(R.id.BTN_TEST)
    

    After doing this, you can call methods on it to change it’s visual or functional purposes in Kotlin.

    Login or Signup to reply.
  6. you can use kotlin view binding

    android {
        buildFeatures {
            viewBinding = true
        }
    }
    
    plugins {
        kotlin("android.extensions")
    }
    
    private lateinit var binding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(view)
       
        val button = binding.BTN_test
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search