Fact0Log
Fact0Log

Reputation: 58

Setting onClick function in Android Studio (Kotlin) shows an error message

I am building a little app in Android Studio using Kotlin. In one of my activities I have a button which when pressed I want it to call a function. For this I use the onClick attribute in the activity_main.xml android:onClick="". What I want to be able to do is display some information based on the user inputs and update a textView in the same activity.

What I am doing now is setting the onClick attribute to android:onClick"getResult". The issue I run into is that it requires to have a parameter 'public void getResult(android.view.View)' and what I don't know how to do is what parameter to pass as android.view.view in my getResult() function when I call it in my code.

Here is the complete signature of getResult()

fun getResult(view: View){
    //do stuff
    }

Upvotes: 1

Views: 1924

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363479

In your case you have to use:

/** Called when the user touches the button */
fun getResult(view: View){
    //view.method()
    //(view as Button).method()
}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • The value for this attribute must be the name of the method you want to call in response to a click event.
  • The method is hosted in the Activity
  • Be public
  • Return void
  • Define a View as its only parameter. This will be the View that was clicked.

You can also declare the click event handler programmatically settign the View.OnClickListener:

val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
    //..
}

Upvotes: 1

Related Questions