如何将参数传递给OnClickListener?

时间:2022-06-01 15:15:27

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个听众,将字符串传递给他们会很棒,他们可以做完全不同的事情。

8 个解决方案

#1


139  

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
     }

  };

#2


17  

Another solution for that issue, you can create a regular method and pass to it the View you want to add the onClickListener to it, and pass the parameters you want to use along with it:

对于该问题的另一个解决方案,您可以创建一个常规方法并将要向其添加onClickListener的View传递给它,并传递您要使用的参数:

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)

           }
    });
}

#3


7  

  1. Have your activity implement View.OnClickListener
  2. 让您的活动实现View.OnClickListener
  3. Register your buttons to the listener
  4. 将您的按钮注册到收听者
  5. Check which button is clicked in onClick
  6. 检查onClick中单击了哪个按钮
  7. 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
           }
       }
    }
    

#4


6  

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);

#5


0  

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)
        }
}

#6


0  

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

如果您有与视图关联的静态内容,则另一个选项是使用HashMap将视图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:

然后从onClick中的视图ID中获取值:

public void onClick(View v) {

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

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

这比使用一长串开关盒更清洁。

#7


0  

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)) }
        }
    }

#8


-1  

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
}

#1


139  

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
     }

  };

#2


17  

Another solution for that issue, you can create a regular method and pass to it the View you want to add the onClickListener to it, and pass the parameters you want to use along with it:

对于该问题的另一个解决方案,您可以创建一个常规方法并将要向其添加onClickListener的View传递给它,并传递您要使用的参数:

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)

           }
    });
}

#3


7  

  1. Have your activity implement View.OnClickListener
  2. 让您的活动实现View.OnClickListener
  3. Register your buttons to the listener
  4. 将您的按钮注册到收听者
  5. Check which button is clicked in onClick
  6. 检查onClick中单击了哪个按钮
  7. 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
           }
       }
    }
    

#4


6  

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);

#5


0  

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)
        }
}

#6


0  

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

如果您有与视图关联的静态内容,则另一个选项是使用HashMap将视图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:

然后从onClick中的视图ID中获取值:

public void onClick(View v) {

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

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

这比使用一长串开关盒更清洁。

#7


0  

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)) }
        }
    }

#8


-1  

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
}