programming
button creation
coding tutorial
software development
UI design

How to create a button programmatically?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a button programmatically means building the UI element in code instead of declaring it in a markup or designer file. This is useful when the number of buttons is dynamic, when the label depends on runtime data, or when the layout must be generated from configuration.

The exact API changes by platform, but the pattern is consistent: instantiate the button, set its properties, attach a click handler, and add it to a parent container.

The Core Steps

No matter the framework, programmatic button creation usually involves four steps:

  • create the button object
  • set text, size, or styling
  • attach the click action
  • add it to the UI hierarchy

If you skip the last step, the button exists in memory but never appears on screen.

Example in JavaScript for the Web

A browser example is the easiest place to see the pattern clearly.

html
1<!doctype html>
2<html>
3  <body>
4    <div id="container"></div>
5    <script>
6      const button = document.createElement('button');
7      button.textContent = 'Click me';
8      button.addEventListener('click', () => {
9        alert('Button clicked');
10      });
11      document.getElementById('container').appendChild(button);
12    </script>
13  </body>
14</html>

The button is created entirely in code and then attached to an existing DOM node.

Example in Android With Kotlin

In Android, you create a Button, configure layout parameters, attach a listener, and add it to a parent layout.

kotlin
1import android.os.Bundle
2import android.widget.Button
3import android.widget.LinearLayout
4import android.widget.Toast
5import androidx.appcompat.app.AppCompatActivity
6
7class MainActivity : AppCompatActivity() {
8    override fun onCreate(savedInstanceState: Bundle?) {
9        super.onCreate(savedInstanceState)
10
11        val layout = LinearLayout(this).apply {
12            orientation = LinearLayout.VERTICAL
13        }
14
15        val button = Button(this).apply {
16            text = "Tap me"
17            setOnClickListener {
18                Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show()
19            }
20        }
21
22        layout.addView(button)
23        setContentView(layout)
24    }
25}

This is useful for dynamic forms, survey screens, or admin UIs built from server-driven configuration.

Example in Swift With UIKit

The same pattern appears in UIKit.

swift
1import UIKit
2
3class ViewController: UIViewController {
4    override func viewDidLoad() {
5        super.viewDidLoad()
6
7        let button = UIButton(type: .system)
8        button.setTitle("Press", for: .normal)
9        button.frame = CGRect(x: 40, y: 100, width: 120, height: 44)
10        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
11
12        view.addSubview(button)
13    }
14
15    @objc private func buttonTapped() {
16        print("Button tapped")
17    }
18}

Again, the button is only visible because it is added to the parent view with addSubview.

When Programmatic Creation Is a Better Choice

Programmatic UI is especially useful when:

  • controls depend on runtime data
  • you are building repeated or generated forms
  • the layout is too dynamic for static markup
  • you want reusable helper methods or view factories

If the UI is mostly fixed and declarative tooling is available, static layout files can still be easier to read and maintain.

Keep Behavior and Layout Cleanly Separated

A common mistake in programmatic UI code is mixing too much logic into one long method. A better pattern is to separate:

  • control creation
  • style configuration
  • event binding
  • layout placement

That makes dynamic UI much easier to change later.

For example, instead of writing ten property assignments inline everywhere, create a helper that returns a configured button.

Common Pitfalls

A common mistake is creating the button but never adding it to a visible parent container.

Another mistake is forgetting layout constraints or size settings, which can leave the button technically present but off-screen or zero-sized.

Developers also sometimes attach event handlers multiple times when controls are recreated during state updates.

Finally, do not default to programmatic UI for everything. It is powerful, but it can become harder to scan than declarative layout files if the screen is mostly static.

Summary

  • Programmatic button creation follows the same pattern on every platform: create, configure, bind, and attach.
  • It is most useful when buttons depend on runtime data or dynamic layout decisions.
  • The button will not appear until it is added to the parent UI hierarchy.
  • Keep styling, event wiring, and layout readable instead of packing everything into one block.
  • Choose programmatic UI when the interface is dynamic, not just because it is possible.

Course illustration
Course illustration

All Rights Reserved.