I want to call this method
public void openButton(View view) {
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
from simple method like this
public void simple(){
openButton();
}
but I can't do it because openButton needs one parameter View. How?
Parameter view is the actual view (button in your case) that was clicked. With this, you can assign multiple buttons to invoke the same method and inside the method check which button was clicked.
There are two ways to call a method with parameters in java: Passing parameters of primtive data type and Passing parameters of reference data type. 4. in Java, Everything is passed by value whether it is reference data type or primitive data type.
To call a method in Java, you type the method's name, followed by brackets. This code simply prints “Hello world!” to the screen. Therefore, any time we write helloMethod(); in our code, it will show that message to the screen.
The Android SDK provided a method: findViewById() . Functionality-wise, this method performs a singular task — it will give you the reference to the view in XML layouts by searching its ID.
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);
}
});
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With