【问题标题】:Call method which needs parameters using android:onClick in XML在 XML 中使用 android:onClick 调用需要参数的方法
【发布时间】:2017-12-16 02:47:37
【问题描述】:

我有一个Button,它是在 XML 中定义的。我正在使用android:onClick 调用一个名为showMessage 的方法。简单方法示例:

    public void showMessage(View v){
    Log.w(TAG, "Hi");
    }

现在假设我的方法需要一个 boolean 和一个 int 作为参数,如何执行以下操作:

android:onClick="showMessage(boolean isExpensive, int money)"

【问题讨论】:

  • AFAIK 不能那样工作。使用来自布局 XML 的回调是有限的。如果你想要更复杂的东西,只需View.setOnClickListener()
  • 你做不到。 onclick 是 android 的 inbuild 方法,它只有一个参数是 clicked view。
  • How to pass parameters to OnClickListener? 的可能副本。显示了一个出色的解决方案
  • 感谢 cmets,我知道我做不到,我只是在寻找解决办法。 @DerGolem 如果我必须在代码中调用我的方法,我理解这个例子,但不能完全了解如何在我的 XML 情况下使用它。你能更具体一点吗? :)
  • 正如@yaa110 向您展示的那样-

标签: android xml onclick


【解决方案1】:

不能像你那样传参数,但是可以使用标签:

<Button 
    android:id="@+id/btn1"
    android:tag="false,25"
    android:onClick="showMessage"
/>

<Button 
    android:id="@+id/btn2"
    android:tag="true,50"
    android:onClick="showMessage"
/>

在你的 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】:

使用 onclicklistener 不是更容易吗?

用 id 定义按钮:

        <Button
        android:id="@+id/button1"
        /.. more attributes here ../
        android:text="@string/something" />

在你的活动中:

Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {          
    @Override
    public void onClick(View v) {
        Log.w(TAG, "Hi");
        }});

【讨论】:

    【解决方案3】:

    你可以这样做: 在 activity.java 中定义另一个不带参数的函数。 通过单击按钮调用此函数。

    使用您要传递的参数创建您的实际函数。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 2019-01-02
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多