Search code examples
androidxmlpreview

Android Studio: Can you display a view just for preview?


My app has a lot of views that are containers for fragments (which load an image and other views) and depend on an API to fetch images. To make the development of the design easier, I like to add a sample of that image in my xml. Right now, I'm adding a RelativeLayout with the FragmentContainer and a dummy ImageView using different visibility values for android:visibility and tools:visibility.

Is there a better way to show images just for preview purposes ? I'd like to have the preview Views not compiled in the release version.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        tools:adjustViewBounds="true"
        tools:src="@drawable/image"
        tools:visibility="visible" />

    <RelativeLayout
        android:id="@+id/FragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Solution

  • If I understood your problem correctly, you could do something like this: instead of using dummy views, use

    <include tools:layout="@layout/layout_preview" layout="@layout/layout_actual"/>
    

    where layout_preview.xml is whatever you want to use only in the preview, and layout_actual.xml is what will be used in the app

    in case you wanted to only add a view in the preview, but have no view at all in the app, you can use a layout_actual.xml with an empty merge tag

    <?xml version="1.0" encoding="utf-8"?>
    <merge xmlns:android="http://schemas.android.com/apk/res/android"/>
    

    if you don't want to include useless layout, you might want to create the dummy ones only for debug build type, it will show an error in the layout because layout_dummy will be missing but since it's tools attribute you should be able to compile and run