How to call method with View Parameter on Android Studio How to call method with View Parameter on Android Studio android android

How to call method with View Parameter on Android Studio


Well, with the code that you provided, you usually use some sort of an onCickListener.

Open your XML file, and add android:onClick="openButton" to the button that you want to call that method. So your XML for the button will look something like this:

<Button   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:text="Click me!"   . . .    android:onClick="openButton" />

That will automatically call that method and pass in a view.

The other option, as BatScream mentioned in the comments, is to just pass in null, as you aren't using the view anyway. HOWEVER, this is bad practice - it'll work this time, but in general, you should follow the system that Android uses. Just go with an onClick in the XML.


If you HAVE to use simple the way it is, do it this way:

public void simple(){    openButton(null);}


You should be able to do

 button.performClick(); 

assuming openButton() is the method assigned to buttons onClick. Meaning, somewhere in your xml you probably have a Button with android:onClick="openButton". Then if you have that Button instantiated and assigned to the variable button, calling the View's performClick() method would call openButton()


Simple. Just pass the view in arguments.

Way 1: if you are calling openButton() method from layout file then, simply call method the following way by applying onClick attribute

<Button   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:text="Go to next screen"   . . .    android:onClick="openButton" />

Way 2: if you are trying to call it from button's onclick by setting OnClickListener, then, simply pass the view you are getting inside OnClickListener's onClick(View view) method as follows:

button.setOnClickListener(new OnClickListener(){    @override    public void onClick(View view)    {       openButton(view);    }});