Monday 14 December 2020

Can I show a sample view when the layout is normally empty & only populated programmatically?

I have a linear layout that I normally add ImageViews to programmatically, but I'd like to render better previews inside Android Studio when looking at layouts.

I can't use tools:src as mentioned here because I don't have any ImageView at all in the XML until runtime.

As a really naive approach, this works visually in Android Studio:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <include tools:layout="@layout/some_sample_layout"/>
</LinearLayout>

If @layout/some_sample_layout is then another LinearLayout:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        tools:src="@tools:sample/backgrounds/scenic" />
</LinearLayout>

But while it displays OK in Android Studio, it fails to compile:

Execution failed for task ':app:mergeDebugResources'.
> main_layout.xml: Error: ERROR: [44 68 44 68 25] must include a layout file:///main_layout.xml

Ideally I think that I'm looking for:

  • some way to add an ImageView directly to the main LinearLayout but mark the whole view as "ignore unless tools" or
  • to be able to "swap" in the body of the LinearLayout somehow.

Is this possible with tools at the moment?



from Can I show a sample view when the layout is normally empty & only populated programmatically?

No comments:

Post a Comment