Android
XML
Dimensions
Resource Files
Source Code

Load dimension value from res/values/dimension.xml from source code

Master System Design with Codemia

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

Introduction

Android dimensions defined in res/values files keep UI sizing consistent across screens and densities. Loading those values from source code is straightforward, but choosing the right API matters because some methods return pixels as float while others round to integers. Understanding that distinction helps you avoid subtle spacing bugs.

Defining Dimensions in XML

A common setup is one dimensions file for spacing, text sizes, and component metrics.

xml
1<resources>
2    <dimen name="spacing_small">8dp</dimen>
3    <dimen name="spacing_medium">16dp</dimen>
4    <dimen name="card_corner_radius">12dp</dimen>
5    <dimen name="title_text_size">18sp</dimen>
6</resources>

Keep names semantic rather than numeric only. Names like spacing_medium are easier to evolve than padding_16 when design tokens change later.

Loading Dimension Values in Kotlin

Use resources.getDimension when you need a float pixel value.

kotlin
val smallPx: Float = resources.getDimension(R.dimen.spacing_small)
val radiusPx: Float = resources.getDimension(R.dimen.card_corner_radius)

Use getDimensionPixelSize when you need an integer pixel count suitable for layout params and margins.

kotlin
1val mediumPxInt: Int = resources.getDimensionPixelSize(R.dimen.spacing_medium)
2
3val params = view.layoutParams
4params.height = mediumPxInt * 3
5view.layoutParams = params

getDimensionPixelOffset is another variant that truncates instead of rounding. Most UI code should prefer getDimensionPixelSize for predictable visual results.

Access from Fragments, Views, and Adapters

Context location affects how you access resources, but the principle is the same.

Fragment example:

kotlin
1class ProfileFragment : Fragment(R.layout.fragment_profile) {
2    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
3        val pad = resources.getDimensionPixelSize(R.dimen.spacing_medium)
4        view.setPadding(pad, pad, pad, pad)
5    }
6}

Custom view example:

kotlin
1class BadgeView @JvmOverloads constructor(
2    context: Context,
3    attrs: AttributeSet? = null
4) : View(context, attrs) {
5
6    private val cornerRadius = resources.getDimension(R.dimen.card_corner_radius)
7
8    override fun onDraw(canvas: Canvas) {
9        super.onDraw(canvas)
10        // draw with cornerRadius
11    }
12}

RecyclerView adapter example:

kotlin
1class UserAdapter(private val context: Context) : RecyclerView.Adapter<UserHolder>() {
2    private val spacing = context.resources.getDimensionPixelSize(R.dimen.spacing_small)
3
4    override fun onBindViewHolder(holder: UserHolder, position: Int) {
5        holder.itemView.setPadding(spacing, spacing, spacing, spacing)
6    }
7}

Jetpack Compose Equivalent

In Compose, load dimensions using dimensionResource to keep parity with XML tokens.

kotlin
1@Composable
2fun ProfileCard() {
3    val pad = dimensionResource(id = R.dimen.spacing_medium)
4    val radius = dimensionResource(id = R.dimen.card_corner_radius)
5
6    Card(shape = RoundedCornerShape(radius), modifier = Modifier.padding(pad)) {
7        Text("Profile")
8    }
9}

This makes migration from XML-based layouts smoother because design tokens remain centralized.

Testing and Maintainability

Resource values can differ by qualifiers such as values-sw600dp for tablets. Automated UI tests should verify layouts on at least one phone and one tablet profile so token changes do not break spacing in larger form factors.

Use one dimensions source for each design system tier and avoid scattering hardcoded values in code. Centralized resources improve consistency and simplify theme adjustments.

Java API Equivalent

If parts of your codebase are still Java, the same resource APIs are available with nearly identical semantics.

java
1int medium = getResources().getDimensionPixelSize(R.dimen.spacing_medium);
2float radius = getResources().getDimension(R.dimen.card_corner_radius);
3
4View card = findViewById(R.id.card);
5card.setPadding(medium, medium, medium, medium);

This makes mixed Kotlin and Java modules easier to maintain while sharing one dimensions source.

When dimensions change as part of a redesign, update XML tokens first and let both Java and Kotlin callers consume the new values automatically. This reduces migration risk and keeps visual behavior aligned across modules.

Common Pitfalls

  • Using hardcoded pixel values in source code. Fix by referencing R.dimen values everywhere.
  • Mixing getDimension and integer layout params incorrectly. Fix by using getDimensionPixelSize for size and margin ints.
  • Naming tokens by numeric values only. Fix by using semantic names tied to UI intent.
  • Defining too many near-duplicate dimensions. Fix by consolidating tokens into a manageable scale.
  • Forgetting qualifier-specific resources. Fix by testing on different device buckets and adding overrides only when necessary.

Summary

  • Define reusable dimensions in XML to keep UI sizing consistent.
  • Use getDimension for float pixels and getDimensionPixelSize for integer sizes.
  • Access resources similarly across activities, fragments, views, and adapters.
  • Use dimensionResource in Compose for shared design tokens.
  • Centralize and test resource tokens to prevent layout drift.

Course illustration
Course illustration

All Rights Reserved.