当布局通常为空且仅以编程方式填充时,我可以显示示例视图吗?

ano*_*ave 7 android android-layout

我有一个通常ImageViews以编程方式添加的线性布局,但我想在查看布局时在 Android Studio 中呈现更好的预览。

我不能tools:src 像这里提到的那样使用因为在运行之前我在 XML 中根本没有任何 ImageView。

作为一种非常天真的方法,这在 Android Studio 中可以直观地工作:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <include tools:layout="@layout/some_sample_layout"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

如果@layout/some_sample_layout是然后另一个 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>
Run Code Online (Sandbox Code Playgroud)

但是当它在 Android Studio 中显示 OK 时,它无法编译:

Execution failed for task ':app:mergeDebugResources'.
> main_layout.xml: Error: ERROR: [44 68 44 68 25] must include a layout file:///main_layout.xml
Run Code Online (Sandbox Code Playgroud)

理想情况下,我认为我正在寻找:

  • 将 ImageView 直接添加到主LinearLayout视图的某种方法,但将整个视图标记为“除非工具,否则忽略”或
  • 能够以某种方式在 LinearLayout 的主体中“交换”。

目前使用工具可以做到这一点吗?

mic*_*377 2

我认为在 AS 设计器中显示动态膨胀视图的最干净、最通用的方法是使用<include />标签,与您的示例非常相似。

我们的<include />标签必须具有layout属性,才能使应用程序可构建。我们可以通过将虚拟布局附加到<merge />root 来省略它。因为它没有孩子,所以任何视图都不会膨胀。

普遍的lt_merge_empty.xml

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

    <!--
        Empty merge tag, so we can use <include/> to show dynamically inflated layouts in designer windows
        For example:

        <include
                tools:layout="@layout/your_inflated_layout"
                layout="@layout/lt_merge_empty"
                />
    -->

</merge>
Run Code Online (Sandbox Code Playgroud)

然后在您的布局中使用它:

<include
        tools:layout="@layout/your_inflated_layout"
        layout="@layout/lt_merge_empty"
        />
Run Code Online (Sandbox Code Playgroud)

请注意:由于某种原因,tools:layout必须放置在layout属性之上,否则它不会被渲染。

编辑:这种方法比@Sina的方法更通用,因为通常您会想要显示动态膨胀的确切布局,所以显然您不能将其更改android:visibilitygone.