Android 如何将参数传递给 OnClickListener?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10614696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:23:45  来源:igfitidea点击:

How to pass parameters to OnClickListener?

androidonclicklistener

提问by Adam Varhegyi

How can i pass parameter to an OnClickListener() ?

如何将参数传递给 OnClickListener() ?

Got my Listener:

得到了我的听众:

   OnClickListener myListener = new OnClickListener()
   {

     @Override
     public void onClick(View v)
     {
         //I want to reach params here

     }

  };

I got 12 buttons and i dont want to write 12 listeners for them, it would be great to just pass a string to them and they can do completly different things.

我有 12 个按钮,我不想为它们编写 12 个监听器,只需将一个字符串传递给它们就太好了,它们可以做完全不同的事情。

回答by Sherif elKhatib

Use your own custom OnClickListener

使用您自己的自定义 OnClickListener

public class MyLovelyOnClickListener implements OnClickListener
   {

     int myLovelyVariable;
     public MyLovelyOnClickListener(int myLovelyVariable) {
          this.myLovelyVariable = myLovelyVariable;
     }

     @Override
     public void onClick(View v)
     {
         //read your lovely variable
     }

  };

回答by Muhammed Refaat

Another solution for that issue,you can create a regular method and pass to it the Viewyou want to add the onClickListenerto it, and pass the parametersyou want to use along with it:

该问题的另一个解决方案,您可以创建一个常规方法并将View您想要添加到它的方法传递onClickListener给它,并传递您想要与它一起使用的参数

Button b1 = new Button();
String something = "something";
Button b2 = new Button();
String anotherSomething = "anotherSomething";
setOnClick(b1, something);
setOnClick(b2, anotherSomething);

private void setOnClick(final Button btn, final String str){
    btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                  // Do whatever you want(str can be used here)

           }
    });
}

回答by Gravitoid

I know this is a late answer but hopefully it can help someone. None of the existing answers worked in my situation but I ended up using the setTag feature of an image that was acting like a button. My account info was in a global member variable that was set up when the activity started.

我知道这是一个迟到的答案,但希望它可以帮助某人。现有的答案都不适用于我的情况,但我最终使用了像按钮一样的图像的 setTag 功能。我的帐户信息位于活动开始时设置的全局成员变量中。

In this case I am setting up a table with each row being an account. The account details are shown when the image is clicked (the image is just an info icon).
Thus:

在这种情况下,我正在设置一个表,每一行都是一个帐户。单击图像时会显示帐户详细信息(图像只是一个信息图标)。
因此:

// prior code....
// NOTE: oneAccount is an object (AccountInfo) holding information about the account

// column with the "detail" arrow
image1 = new ImageView(this);
image1.setImageResource(R.drawable.info);
image1.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
image1.setPadding(15, 1, 15, 1);
image1.setTag(oneAccount);
// add a listener to go to that account detail on a click
image1.setOnClickListener(new TextView.OnClickListener() {
    public void onClick(View v) {
    // change the color to signify a click
    v.setBackgroundColor(getResources().getColor(R.color.button_selected));


    // get what we need out of the tag
    AccountInfo thisAcct = (AccountInfo) v.getTag();

        // your code would do other stuff here

}
});

// add the image to the table row
tr1.addView(image1);

回答by Mark Pazon

  1. Have your activity implement View.OnClickListener
  2. Register your buttons to the listener
  3. Check which button is clicked in onClick
  4. Process your string depending on which button was clicked

    public class _Test2Activity extends Activity implements OnClickListener {
    
       private Button button1;
       private Button button2;
       private Button button3;
    
       private String myString;
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
    
         button1 = (Button)findViewById(R.id.button1);
         button2 = (Button)findViewById(R.id.button2);
         button3 = (Button)findViewById(R.id.button3);
    
         button1.setOnClickListener(this);
         button2.setOnClickListener(this);
         button3.setOnClickListener(this);   
    
         myString = "This is a string";
    
       } 
    
       @Override
       public void onClick(View v) {
           if(v==button1) {
              //do something with myString
           } else if(v==button2) {
              //do something with myString
           } else if (v==button3) {
              //do something with myString
           }
       }
    }
    
  1. 让您的活动实现 View.OnClickListener
  2. 将您的按钮注册到侦听器
  3. 检查 onClick 中点击了哪个按钮
  4. 根据单击的按钮处理您的字符串

    public class _Test2Activity extends Activity implements OnClickListener {
    
       private Button button1;
       private Button button2;
       private Button button3;
    
       private String myString;
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
    
         button1 = (Button)findViewById(R.id.button1);
         button2 = (Button)findViewById(R.id.button2);
         button3 = (Button)findViewById(R.id.button3);
    
         button1.setOnClickListener(this);
         button2.setOnClickListener(this);
         button3.setOnClickListener(this);   
    
         myString = "This is a string";
    
       } 
    
       @Override
       public void onClick(View v) {
           if(v==button1) {
              //do something with myString
           } else if(v==button2) {
              //do something with myString
           } else if (v==button3) {
              //do something with myString
           }
       }
    }
    

回答by Suragch

If you have static content associated with the view, another option is to use a HashMapto map the view id to the content.

如果您有与视图关联的静态内容,另一种选择是使用 aHashMap将视图 ID 映射到内容。

private static Map<Integer, String> idToStringMap = new HashMap<Integer, String>();

Initialize the map in onCreate:

初始化地图onCreate

idToStringMap.put(R.id.button1, "hello");
idToStringMap.put(R.id.button2, "world");
// ...

Then get the value from the view id in onClick:

然后从视图 id 中获取值onClick

public void onClick(View v) {

    String myString = idToStringMap.get(v.getId());
}

This is a little cleaner than using a long set of switch cases.

这比使用一长串开关盒要干净一些。

回答by Shraddha Patel

Note that you do this in Kotlin a little differently from how you do it in Java. In Kotlin, you append NameOfParentClass()to the subclass declaration.

请注意,在 Kotlin 中执行此操作与在 Java 中执行此操作的方式略有不同。在 Kotlin 中,您附加NameOfParentClass()到子类声明。

Now override Activity‘s onCreate()method. It will look something like this.

现在覆盖 Activity 的onCreate()方法。它看起来像这样。

class MainActivity : AppCompatActivity() {
        private var btnClick: Button? = null
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            btnClick = findViewById(R.id.btnClick) as Button
            btnClick!!.setOnClickListener { startActivity(Intent(this@MainActivity, KotlinActivity::class.java)) }
        }
    }

回答by Geet Thakur

In Kotlin :

在科特林:

Here i'm passing a view as a parameter onClickof Another view

这里我传递一个视图作为另一个视图的onClick 参数

define your Handlerclass object first in xml layout like this:

首先在 xml 布局中定义您的Handler类对象,如下所示:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/tools">
    <data>
        <import type="android.view.View" />
        <variable
            name="handler"
            type="com.demoapp.controllers.Handler" />
   </data>

and define button which perform clickfunctionality.

并定义执行点击功能的按钮。

<Button
  android:id="@+id/button2"
  android:onClick="@{(view) -> handler.getbuttonClickEvent(textViewId)}"
  .../>

and your text view like this: remember your TextView idwill be converted like textViewId

你的文本视图是这样的:记住你的TextView id会像textViewId一样被转换

<TextView
        android:id="@+id/text_view_id"
        ... />

final set up method in your Handler class

Handler 类中的最终设置方法

fun getbuttonClickEvent(view: TextView){
        view.text="Hello World"
    }

回答by Joonsung Kim

use implements OnClickListener like below code

使用如下代码实现 OnClickListener

public class Test extends Activity implements OnClickListener{
    Button btn1;
    Button btn2;
    Button btn3;
    Button btn4;
    Button btn5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //initialize btn...~~~

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case will be determine by Button's Id (R.id.blablabla)
        }
}

回答by HANGOZADA

Another solution may be to not write the code directly inside onClick() method, alternatively, write the code in a separate method, and then call that method in onClick().

另一种解决方案可能是不直接在 onClick() 方法中编写代码,或者在单独的方法中编写代码,然后在 onClick() 中调用该方法。

Example:

例子:

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    function();
   }
});

private void function() {
 //your code here
}