Search code examples
javaandroideventsonclickandroid-event

How would I code a button onclick event?


Aim: To have the if statement execute a onclick event through code.

I currently has this button in xml.

<Button 
   android:id="@+id/button1" 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:text="Set Call" 
   android:onClick="makeCall"/>

I have tried R.id.button1.performClick(); but I get

Cannot invoke performClick() on the primitive type int

I have the below conditional to repeat if count is under 5.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    int count=0;

    if (count <= 5) {

       //make call                
       R.id.button1.performClick();

       count++;

       Toast toast=Toast.makeText(this, "Count is currently" + count++ + ", 
                                        repeating", Toast.LENGTH_LONG);
       toast.show();
    }
    else {
       // Toast Popup when call set button pressed
       Toast toast=Toast.makeText(this, "Call count complete, ending method" , 
                                                            Toast.LENGTH_LONG); 
       toast.show(); 

       count++;

    }
}

Solution

  • You need to get a reference to the button, then you can use it.

    Button button1 = yourview.findViewById(r.id.button1);
    button1.performClick();