Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

android - MainActivity.kt doesn't recognise button by ID

I'm struggling with very common problem, I think. I've created a button in xml file and tagged it with ID. Then I wanted to make onClickListener in MainActivity.kt. But when I'm typing button's ID, it's marked red and it seems like Android Studio doesn't recognise it. I've tried cleaning and rebuilding project, but the problem still exist. Invalidate Caches/Restart didn't help as well. Here's XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="@color/backgroundColor"
    android:fadingEdge="vertical"
    android:fadingEdgeLength="80dp"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity"
    tools:viewBindingIgnore="true">

 <Button
        android:id="@+id/btnDateBicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:backgroundTint="#3D446C"
        android:text="Select Date"
        android:textSize="25sp"
        android:textStyle="bold" />
</LinearLayout>

And here's kotlin code

package com.example.ageinminutes

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

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val mybtn = findViewById<btnDateBicker>()
    }
} 
question from:https://stackoverflow.com/questions/65947132/mainactivity-kt-doesnt-recognise-button-by-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you simply want to fetch by id, use findViewById method.

val myBtn: Button = findViewById(R.id.btnDateBicker)

or

val myBtn = findViewById<Button>(R.id.btnDateBicker)

Another way to play with views in the kotlin file:

  1. Try with synthetic binding, like just start writing few words of XML id in your kotlin file and android studio will attach that view for you.

  2. Try with view binding or data binding, you just have to enable these settings in build.gradle file. [More Robust way]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...