I am dynamically creating some buttons and ideally would like to be able to have a method run if the button is pressed.
Is something like the following even possible?
private void someMethod(int ID){
//on button pressed do something with the ID
}
private void otherMethod(){
for( Program element : someList)
{
addButton.setOnClickListener(someMethod(element.getID));
}
}
Obviously thats just a mock up of some code to illustrate my question. I know you can instantiate a new class so it seems like you should be able to call a method although so far I just keep getting errors with my attempts.
I have had a look around the web but can't find anything to answer this, so thought I would ask here.
setOnClickListener defines what will happen when the button is clicked. Setting it multiple times for the same button is meaningless; the last one you set will be the active one.
To call a method within a listener, declare an anonymous class override:
addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
someMethod(...);
}
});
If you're trying to set up multiple buttons with similar functionality, you need to loop through the buttons (in a list, say), and set each of their OnClickListeners. To achieve a differing variable per button, you could use the View's tag:
for (Button b : buttons) {
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
someMethod(v.getTag());
}
});
}
Now you can simply set the Button's tag property in the XML (or manually) to whatever you wish and it will get passed into the listener (and thus the method).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With