Sometimes your android app needs to forego of xml layouts and programmatically generate views instead. This particular example will deal with generating a simple button. Short post because I am tired and I just want to make sure that this is preserved somewhere for me to come back to later.

But, first lets just talk about this really quickly. Why would we need to do this? There’s at least a couple of scenarios where this would be required, actually.

  • You want to create a template Button class that you can then provide to all your activities. Or several Button classes with different Themes.
  • Or, you’re trying to provide Buttons from an API from a web-based backend server. Attributes are being sent through and you need to generate Views from these attributes.

Anyway here’s the code:

//Generally define a method that returns a Button object.
    private Button addButton(Context context, String label, String tag) {
    Button button = new Button(context);
    button.setWidth(getPx(320, context.getResources()));
    button.setHeight(getPx(50, context.getResources()));
    button.setOnClickListener(this); //this refers to the calling activity.
    return button;

You will need a ViewGroup object obviously that will need add this as a child View. To be able to detect when this Button is clicked, we check for the tag from the View Object passed to the onClickListener callback by calling the View.getTag() method.