Kahibaro
Discord Login Register

8.4 View Attributes

Introduction

View attributes are the properties that control how a view looks and behaves in your Android layout. They are written as XML attributes inside view tags and are applied when the layout is inflated. This chapter focuses on the most common and useful view attributes you will use repeatedly, how they interact with each other, and how they differ between layout containers.

Size: width and height

Every view must define how big it should be. In XML, this is done with the android:layout_width and android:layout_height attributes. These two attributes always come from the android: namespace and you must set them for each view.

There are three main ways to specify size. The first is wrap_content. With wrap_content, the view becomes just large enough to fit its content. For example, a TextView with android:layout_width="wrap_content" will be only as wide as needed to show its text.

The second way is match_parent. With match_parent, the view grows to fill all the available space in its parent in the given dimension. For example, a Button with android:layout_width="match_parent" fills the entire width that the parent allows.

The third way is to use an exact dimension. You can give a fixed size such as 100dp. In practice you almost always use density independent pixels, dp, instead of raw pixels. For example:

<TextView
    android:layout_width="200dp"
    android:layout_height="40dp"
    android:text="Fixed size text" />

You can mix these options. A common pattern is to use match_parent for width and wrap_content for height on views that span the screen horizontally but only need enough vertical space for their content.

Always use dp for view sizes, not raw pixels, or your UI will look inconsistent across devices with different screen densities.

Positioning inside the parent

How a view is positioned relative to its parent depends on the type of layout, but there are a few attributes that are shared or have similar concepts.

The basic alignment attribute is android:gravity on the parent and android:layout_gravity on the child when using certain layout types such as LinearLayout. The gravity attribute controls how content is placed inside a view. For example, in a TextView, android:gravity="center" will center the text inside the view’s rectangle.

The layout_gravity attribute is used by some parent layouts to decide where to place each child. For example, inside a LinearLayout, a child can request android:layout_gravity="center_horizontal" so that the parent places the child centered horizontally within the available space.

Each layout type has its own set of layout_ attributes. For instance, LinearLayout supports android:layout_weight, while ConstraintLayout uses app:layout_constraint... attributes. These are layout specific and will be covered in their own chapters. The important point here is that attributes starting with android:layout_ usually describe how the parent should treat this child.

Margins and padding

Margins and padding are similar concepts but affect different sides of the boundary between a view and its surroundings.

Padding is the space inside a view between the view’s border and its content. When you add padding, the content is pushed inward. For example, a TextView with padding will show its text inset from its rectangular boundary. You can set padding with android:padding to apply it on all sides, or with side specific attributes like android:paddingStart, android:paddingEnd, android:paddingTop, and android:paddingBottom.

Margins are the space outside a view between the view’s border and other views or the parent. Margins are defined using android:layout_margin to apply the same margin to all sides, or side specific attributes such as android:layout_marginStart, android:layout_marginEnd, android:layout_marginTop, and android:layout_marginBottom.

Here is an example that uses both:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me"
    android:padding="16dp"
    android:layout_marginTop="24dp"
    android:layout_marginStart="16dp" />

Padding affects the space inside the view and changes where the content is drawn. Margin affects space outside the view and changes distance to neighbors or the parent.

When working with modern layouts, it is better to use paddingStart and paddingEnd instead of paddingLeft and paddingRight. Start and end respect layout direction for right to left languages.

Visibility and presence

Sometimes you need to hide a view. Android provides the android:visibility attribute with three possible values: visible, invisible, and gone.

If visibility is visible, the view is shown normally. If it is invisible, the view is drawn as transparent but still takes up space in the layout. The gap remains, but nothing is rendered. If it is gone, the view is completely removed from the layout. It takes no space, and other views can shift to occupy that area.

This behavior is important when you design dynamic layouts where views may appear and disappear. For example, in a form, you might set an optional field to gone so that other fields move up, instead of simply hiding content and leaving a blank area.

You can change visibility at runtime from code, but in XML you define the default state with android:visibility="gone" or another value.

Text related attributes

Text views share a set of attributes that control how text is displayed. The most basic one is android:text, which holds the string shown in the view. In production code you should not hardcode literal text in your layouts. Instead, you reference a string resource such as @string/hello_world. The mechanism of resources is handled in its own chapter, but you will see the reference pattern often.

The size of the text is controlled by android:textSize. Text size is expressed in sp, scale independent pixels, so that it respects the user’s font size preferences. For example:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/welcome_message"
    android:textSize="18sp" />

The color of the text is defined with android:textColor. You can set a direct color like #FF0000, or reference a color resource with something like @color/primary_text. A placeholder example is:

android:textColor="@android:color/black"

The alignment of text inside the view is controlled with android:gravity. For example android:gravity="center_vertical|center_horizontal" will center text both vertically and horizontally inside the view.

Other common attributes include android:maxLines to limit the number of displayed lines and android:ellipsize="end" to show ... when the text is too long. These attributes affect the behavior of text when space is limited.

Use sp for text size, not dp, to keep text readable when the user changes system font size.

Backgrounds and colors

Every view can have a background, which is drawn behind its content. The most straightforward way to set it is with android:background. This can be a solid color or a drawable resource. For example:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray" />

A background can also be a shape or custom drawable that provides rounded corners or gradients. The concept of drawable resources is covered in a separate chapter, but here it is important to understand that android:background does not have to be only a simple color.

Be aware that background and padding interact. Padding keeps content away from the inside edges of the background. Without padding, text or images can be drawn right up against the edge of the background.

Identifiers and referencing views

To work with a view from Kotlin code, you must give it an identifier in XML. This is done with the android:id attribute. The typical form is:

android:id="@+id/my_button"

The @+id part tells the tools to create a new id resource if it does not already exist. Once the id is defined, you can reference this view in code with the generated reference. How you access views from code will depend on the approach you use, which is covered later. For now, the key idea is that every interactive or important view should have a unique android:id.

You can also reference an existing id without the plus sign. For instance, some layout attributes will reference other views by id, such as in ConstraintLayout, and they use @id/some_view to refer to a view already defined elsewhere in the layout.

Enabled, focusable, and interaction flags

Views that accept user interaction use several attributes to control how they behave. The most fundamental is android:enabled. If this is set to false, the view cannot be interacted with and usually appears dimmed. For example, a disabled button:

<Button
    android:id="@+id/submitButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/submit"
    android:enabled="false" />

Focus behavior is controlled by attributes such as android:focusable and android:focusableInTouchMode. Focus decides which view receives input from keyboards or hardware controllers. On touch only devices you may rarely think about it directly, but it still affects things like which field is active when the screen opens.

There is also android:clickable to control whether tap events are processed. Some views that do not appear interactive by default can be made clickable. However, many widgets, such as Button, are already clickable and you usually set their click behavior in code instead of toggling this attribute unless you have a specific need.

Content description and accessibility attributes

Accessibility is important so that your app can be used by people with disabilities. One essential attribute is android:contentDescription. This provides a textual description of what a view represents. Screen readers use this text to describe the UI to visually impaired users.

For views that display only an image, such as an ImageView used as a button, you should set android:contentDescription to a meaningful phrase. For example:

<ImageView
    android:id="@+id/playButton"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:src="@drawable/ic_play"
    android:contentDescription="@string/play_audio" />

If a view is purely decorative and conveys no information, you can set android:contentDescription="@null" so that accessibility services ignore it and do not read it aloud.

Accessibility has many more aspects, but contentDescription is the primary attribute you will use frequently in XML.

Layout direction aware attributes

Modern apps must support both left to right and right to left languages. To help with this, Android provides layout direction aware attributes. Instead of left and right, use start and end. This applies to padding, margins, and some other alignment attributes.

For example, you can write:

android:paddingStart="16dp"
android:paddingEnd="16dp"

and this padding will automatically flip for right to left layouts. Similarly:

android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"

is preferable to layout_marginLeft and layout_marginRight in new layouts.

Using start and end instead of left and right makes your UI more flexible and easier to localize.

Namespaces and custom attributes

In XML layouts you will usually see multiple namespaces at the top of the root element. Attributes like android:layout_width belong to the Android framework namespace. You may also see attributes with app: prefix. Those belong to the application namespace, which is usually used for support library and custom attributes.

For example, ConstraintLayout uses many attributes like app:layout_constraintTop_toTopOf, which do not belong to the android namespace. When you see app: attributes, it means they are defined by libraries or by your own application, not by the base framework.

You use android: for standard attributes that exist on all supported devices, and app: or other prefixes for attributes provided by external libraries or your project. The layout editor in Android Studio will usually suggest the correct namespace as you type.

Using dimension and color resources in attributes

Most attributes that accept sizes or colors can reference resource values instead of literal values. This helps you keep the design consistent and easier to change.

For dimensions, you can use @dimen/some_name. That dimension is defined in a resource file and might be something like 16dp. In a view attribute, it looks like:

android:padding="@dimen/default_padding"

For colors, you can use @color/some_color. For example:

android:textColor="@color/primaryTextColor"

Using resources instead of hardcoded values lets you adjust the look of your entire app by changing one resource value, and it also supports themes and styles which you will explore later.

Summary

View attributes are the building blocks that define how each view in your layout looks, how big it is, how it aligns with neighbors, and how it behaves. You control size with layout_width and layout_height, spacing with padding and margins, appearance with text and background attributes, visibility with the visibility flag, and interaction with id and enabled related attributes. As you build more complex layouts, you will combine these base attributes with layout specific ones and with styles and themes, but the concepts in this chapter remain at the core of every view you place on the screen.

Views: 2

Comments

Please login to add a comment.

Don't have an account? Register now!