Call method that requires parameters using android: onClick in XML
I have Button
and it is defined in XML. I am using android:onClick
to call a method named showMessage
. An example of a simple method:
public void showMessage(View v){
Log.w(TAG, "Hi");
}
Now suppose my method needs, for example, boolean and int parameters , how to do something like:
android:onClick="showMessage(boolean isExpensive, int money)"
source to share
It is not possible to pass parameters in the same way as you, but you can use tags:
<Button
android:id="@+id/btn1"
android:tag="false,25"
android:onClick="showMessage"
/>
<Button
android:id="@+id/btn2"
android:tag="true,50"
android:onClick="showMessage"
/>
and in your java:
public void showMessage(View v) {
String tag = v.getTag().toString();
boolean isExpensive = Boolean.parseBoolean(tag.split(",")[0]);
int money = Integer.parseInt(tag.split(",")[1]);
this.showMessage(isExpensive, money);
}
public void showMessage(boolean isExpensive, int money) {
// Your codes here
}
Wouldn't it be easier to use onclicklistener?
Define a button with id:
<Button
android:id="@+id/button1"
/.. more attributes here ../
android:text="@string/something" />
and in your activity:
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.w(TAG, "Hi");
}});
source to share
You can do it like this: Define another function in activity.java with no argument. Call this function by pressing the button.
Make your actual function the argument you want to pass.
public void showMessageToClick(View v){
// define your bool as per your need
boolean isExpensive = true;
int money=30000;
showMessage(isExpensive, money)
Log.w(TAG, "Hi");
}
showMessage(boolean isExpensive, int money){
// your code here
}
source to share