Button Creation
Programming
Background Image
UI Design
Code Example

Create a button programmatically and set a background image

Master System Design with Codemia

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

Introduction

Creating buttons programmatically is useful when UI elements depend on runtime data, feature flags, or dynamic layouts. Setting a background image correctly requires platform specific APIs and attention to scaling and accessibility. A reliable implementation combines visual styling, layout constraints, and state aware behavior.

Android Example In Kotlin

In Android, create the button in code, assign layout parameters, and set a drawable background.

kotlin
1import android.os.Bundle
2import android.util.TypedValue
3import android.widget.Button
4import android.widget.LinearLayout
5import androidx.appcompat.app.AppCompatActivity
6import androidx.core.content.ContextCompat
7
8class MainActivity : AppCompatActivity() {
9    override fun onCreate(savedInstanceState: Bundle?) {
10        super.onCreate(savedInstanceState)
11
12        val root = LinearLayout(this).apply {
13            orientation = LinearLayout.VERTICAL
14            val pad = TypedValue.applyDimension(
15                TypedValue.COMPLEX_UNIT_DIP, 16f, resources.displayMetrics
16            ).toInt()
17            setPadding(pad, pad, pad, pad)
18        }
19
20        val button = Button(this).apply {
21            text = "Continue"
22            background = ContextCompat.getDrawable(context, R.drawable.bg_button)
23            setTextColor(ContextCompat.getColor(context, android.R.color.white))
24        }
25
26        root.addView(button, LinearLayout.LayoutParams(
27            LinearLayout.LayoutParams.MATCH_PARENT,
28            LinearLayout.LayoutParams.WRAP_CONTENT
29        ))
30
31        setContentView(root)
32    }
33}

Use density independent dimensions and optimized drawable assets for consistent rendering.

iOS Example In Swift

For UIKit, create UIButton, set image background for control states, and apply Auto Layout constraints.

swift
1import UIKit
2
3class ViewController: UIViewController {
4    override func viewDidLoad() {
5        super.viewDidLoad()
6
7        let button = UIButton(type: .system)
8        button.translatesAutoresizingMaskIntoConstraints = false
9        button.setTitle("Continue", for: .normal)
10        button.setTitleColor(.white, for: .normal)
11        button.setBackgroundImage(UIImage(named: "button_bg"), for: .normal)
12
13        view.addSubview(button)
14
15        NSLayoutConstraint.activate([
16            button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
17            button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
18            button.heightAnchor.constraint(equalToConstant: 48),
19            button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
20        ])
21    }
22}

Always provide appropriately sized images for different device scale factors.

Web Example With JavaScript

For web UIs, create the element with JavaScript and style using CSS background properties.

html
1<!doctype html>
2<html>
3<head>
4  <style>
5    .cta {
6      width: 220px;
7      height: 48px;
8      color: #fff;
9      border: none;
10      cursor: pointer;
11      background: url("button-bg.png") center/cover no-repeat;
12      font-size: 16px;
13    }
14  </style>
15</head>
16<body>
17  <script>
18    const btn = document.createElement("button");
19    btn.className = "cta";
20    btn.textContent = "Continue";
21    btn.addEventListener("click", () => console.log("clicked"));
22    document.body.appendChild(btn);
23  </script>
24</body>
25</html>

For modern design systems, prefer CSS classes over inline styles so themes remain maintainable.

State Handling And Accessibility

Background image buttons must still communicate state changes.

  • Provide disabled and pressed visual states.
  • Maintain sufficient text contrast over background images.
  • Include accessible labels and tap targets that meet platform guidance.

On iOS and Android, minimum touch areas are important for usability. On web, keyboard focus styling is critical for accessibility.

Asset Optimization

Use compressed images and choose vector assets where possible. Oversized images increase memory usage and startup time, especially on lower end devices. Keep naming conventions clear so dynamic asset selection remains predictable.

If background images contain text, replace embedded text with real button titles to preserve localization and accessibility.

Testing Across States And Devices

Programmatically built buttons should be tested under dark and light themes, different font scales, and right to left locales. These checks catch clipping and contrast issues that do not appear in a single default simulator run.

Automated UI tests can assert that the button remains tappable, visible, and correctly labeled after rotation and layout changes. If your app supports dynamic theming, verify that image based backgrounds still work when brand colors change.

For reusable components, encapsulate button creation logic in one helper or UI factory method. Centralized construction reduces inconsistency and makes later design updates faster.

Common Pitfalls

  • Setting background images without defining pressed and disabled states.
  • Using fixed pixel sizes that do not adapt to screen density.
  • Embedding text inside image assets instead of real button labels.
  • Ignoring contrast and accessibility requirements.
  • Creating heavy image assets that slow initial render.

Summary

  • Programmatic button creation supports dynamic UI use cases.
  • Apply background images with platform specific APIs and layout constraints.
  • Add state aware styling for pressed, disabled, and focus states.
  • Optimize image assets for memory and rendering performance.
  • Keep accessibility and localization requirements central to implementation.

Course illustration
Course illustration

All Rights Reserved.