问题
I have a Button
and it is defined in XML. I am using android:onClick
to call a method called showMessage
. Simple method example:
public void showMessage(View v){
Log.w(TAG, "Hi");
}
Now suppose my method needs for example a boolean and an int as parameters, how to do something like:
android:onClick="showMessage(boolean isExpensive, int money)"
回答1:
It is not possible to pass parameters as you did, 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
}
回答2:
Wouldn't it be easier to use an onclicklistener?
Define the 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");
}});
回答3:
You can do it this way: Define another function in the activity.java without the argument. Call this function from the button click.
Make your actual function with the 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
}
来源:https://stackoverflow.com/questions/27192219/call-method-which-needs-parameters-using-androidonclick-in-xml