Boreena Boreena - 6 months ago 19
Android Question

android onclicklistener on class with button inside?

I made an app that creates 3 buttons dynamically. For certain reasons I needed to create every button from a class I made.

inside this class I wrote this:

public class FloatButton{
public void generate(String text, final Context context){


Button button = new Button(context);
button.setText(text);
}


now in my main activity I create a object of this class:

FloatButton floatButton = new FloatButton();
floatButton.generate("float Button", this);


now to the problem... I need to add an individual onclick listener to each button. I want to interact with other buttons of the class by clicking a button. That's why I need to write the onclick listener into my main activity and not into the FloatButton class. So I tried the following:

floatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

}
});


this didn't work because the floatButton object doesn't have the setOnClickListener method because it is not part of the button class.

Also I tried to set an Id for the button inside the class. Therefore the class would look like this:

public class FloatButton{
public void generate(String text, int id, final Context context){


Button button = new Button(context);
button.setId(id);
button.setText(text);

}
}


now I hoped to set the onclicklistener by the button id:

final OnClickListener listener = new View.OnClickListener() {

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.1:
...
break;
case R.id.2:
...
break;
}
}


Sadly the R.id. ... doesn't work neither because the Id is only available if the buttons are already created.

So what else can I try to do?

Answer

change your generate function to

public Button generate(String text, final Context context){
        Button button = new Button(context);
        button.setText(text);
        return button;
} 

then set listener on the returned object in activity

Button generated =  floatButton.generate("float Button", this);
generated.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {

     }
});