Android Studio Design Mode: How to Set View Properties for the Preview Only

Most Android developers use the preview functionality of their IDE to see a live version of their XML layouts. Complex designs can be hard to grasp and to adjust. With the preview, you generally are able to get an overview of the layout simulated on a real device within seconds, without having to compile and deploy a new version of the app. This is especially helpful when dealing with a text-heavy layout with lots of TextViews.

Decision Time

When the text property of a all TextViews is set, the preview will display it quite nicely:

Helpful Preview

As a developer, you see right away how the XML translates into a design. You can even test edge cases by using very long values. The problem is if you're setting the text property, it'll be displayed in the compiled app; unless you overwrite it in your activity code.

Most developers go one of two possible routes here. They either don't set the text property (which means no nice previews, but not additional Java code to reset it):

Useless Preview without Text Property

Otherwise, they use the aforementioned text property and resetting the text in code. Neither of them is optimal and a small gem of Android development makes things easier:

Using Tools as Design Mode

This fairly hidden Android tools post explains how to use the tools namespace to achieve both things at the same time: design and code efficiency.

First, add xmlns:tools="http://schemas.android.com/tools" to your root element of the design:

<LinearLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    ...

Then, in your TextView element, instead of using android:text, use tools:text for content which should be displayed in the preview, but not in the actual app.

<TextView  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    tools:text="Merchant Name"/>

Of course, you can continue to use the android:text property to set the TextView for the app run time:

<TextView  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:text="Show only in app"
    tools:text="Show only in IDE preview"/>

While we only talk about TextViews here, this can be used for any standard XML layout property. With that in mind, you'll be able to set preview specific values for a faster design process of the app, while keeping your production code clean from any unnecessary clutter.

If you want to continue to improve your Android skills by learning tipps & tricks, follow us on twitter @futurestud_io.

Explore the Library

Find interesting tutorials and solutions for your problems.