skip to Main Content

I want use android:onClick to access the functions at MainActivity from activity_main.xml but it’s deprecated. Is there another way or replacement for onClick?

Here the code:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="horizontal">

    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="30dp"
        android:id="@+id/btn00"
        android:onClick="click"></Button></LinearLayout>

and my function at MainActivity

fun click(view: View){
        Toast.makeText(applicationContext,"Clicked",Toast.LENGTH_SHORT).show
    }

There is an error saying "Corresponding method handler ‘public void click(android.view.View)’ not found.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks all for the help,

    Turns out I place my function at the wrong place. I'm sorry for the trouble. Turn out it's just a petty mistake :D

    Edit: Turns out i placed my fuction outside of the class


  2. The XML error is because there is no context specified for your layout file. you can specify it in the root element of layout XML file as

    tools:context="yourpackage.MainActivity"
    

    This basically tells the XML to look for click function in MainActivity.

    Other than that this code should run correctly, given that you have specified the correct XML layout in your Activity setContentView.
    point worth noting is that there is always an option to do it
    programmatically in your Activity onCreate

    val button = findViewById<Button>(R.id.btn00)
    button.setOnClickListener{
        Toast.makeText(applicationContext,"Clicked",Toast.LENGTH_SHORT).show()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search