0

I am trying to make an application on android studio and I'm trying it for the first time. I can't make any button clickable. I want to click a button and open another page. setonclicklistener is turning red when I write it. How can I make it work? I'm using Kotlin.

alpheratz
  • 11
  • 4
  • Can you please add the part of your code where you are trying to call setOnClickListener. Thanks. – Ma3x Dec 27 '21 at 18:45
  • 1
    It's ``setOnClickListener`` (capitalisation is important in Kotlin/Java) and you have to make sure you're calling it on something like a ``View`` that actually *has* that method, like ``myButton.setOnClickListener { }``. Honestly you probably want to run through some basic tutorials first ( like at https://developer.android.com/courses/fundamentals-training/toc-v2 ) so you get the hang of everything, it'll save you a lot of time! – cactustictacs Dec 27 '21 at 18:48
  • https://www.youtube.com/watch?v=nZqDnWUZnY0&t=256s i try this as basic and it is red btnClick at MAinActivity.kt – alpheratz Dec 27 '21 at 19:09
  • You need a button with ``android:id="@+id/btnClick"`` in your layout file. That coder is also using synthetic imports, which "magically" creates a variable for each view with an ``id`` in the layout. That's why ``btnClick`` is defined for them, but the IDE doesn't recognise that name in yours. It's deprecated, but here's how you can add it if you really want to: https://antonioleiva.com/kotlin-android-extensions/ Again, I'd *really* recommend you follow some basic, up-to-date tutorials so you develop an understanding of what's going on, especially if most of this doesn't make any sense to you – cactustictacs Dec 28 '21 at 00:45

2 Answers2

1

In onCreateMethod you can simply write

myButton.setOnClickListener{
//your action
}

You can also check https://stackoverflow.com/a/34593645/15529296

Yash Shah
  • 52
  • 4
0

If the whole setOnClickListener function has turned red in Android Studio, it means that you are trying to call it on a class/type that does not have that function, i.e. you are trying to call setOnClickListener on a class that does not extend View. Check the error message and check the class/type that you are trying to call setOnClickListener on and make sure you are calling it on a Button (or any component that is extending a View, or a View itself).

If you are new to Android (Kotlin) programming, check some tutorials for sample applications to get a quick introduction to the concepts that are unique to the Android programming environment.

Ma3x
  • 5,761
  • 2
  • 17
  • 22