onClick event not working on Android Blank Activity

1k views Asked by At

I have a blank activity in Android Studio, and I have performed the following instructions but it is not working when I run the program.

  1. Select the button and look for properties/attributes panel on the right.
  2. Assign the name onClick to the android:onClick property of your Button.

  3. Implement the following method in the Main_Activity file:

public void onClick (View view) { Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show(); } When I try to run this I get errors like:

  • expecting a member declaration
  • function declaration must have a name
3

There are 3 answers

4
abdevwarlock On

1)in Xml file of you Activity set onClick property of button with specified function name android:onClick:"onClick"

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:onClick="onButtonClick"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

2)after this put same function inside your activity but with parameter like this public void onClick (View view)

public void onButtonClick(View view){
   Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show();
}

3) when you click on button provided method gets called

Note: function name can be anything but access specifier, return type and parameter has to be same.

0
Ankit Kumar On
Button yourButton = (Button)findViewById(R.id.your_button_id)  
yourButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show();
        }
    });

Please try this in Java.

0
navylover On

Using the XML attribute android:onClick to trigger a click event. Only need two steps:

1.assign android:onClick to button like this:

 <Button 
    android:id="@+id/button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Click me!" 
    android:onClick="btnClicked" />

2 In activity define a function named btnClicked like this:

   public void btnClicked(View v) { 
            Log.d("MR.bool", "Button1 was clicked "); 
   }

Notice: don't mix this way with setOnClickListener,just only above two steps.