Call method which needs parameters using android:onClick in XML

老子叫甜甜 提交于 2019-12-06 06:27:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!