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

标签 android android-layout

我有一个线性布局,我通常会添加 ImageViews以编程方式,但我想在查看布局时在 Android Studio 中呈现更好的预览。
我无法使用 tools:src as mentioned here因为在运行时之前我在 XML 中根本没有任何 ImageView。
作为一种非常幼稚的方法,这在 Android Studio 中可以直观地工作:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <include tools:layout="@layout/some_sample_layout"/>
</LinearLayout>
如果 @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>
但是当它在 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
理想情况下,我认为我正在寻找:
  • 某种方式可以将 ImageView 直接添加到主 LinearLayout但将整个 View 标记为“忽略工具”或
  • 能够以某种方式在 LinearLayout 的主体中“交换”。

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

    最佳答案

    我认为在 AS 设计器中显示动态膨胀 View 的最简洁和最通用的方法是使用 <include />标签,与您的示例非常相似。
    我们的<include />标签必须有 layout属性,使应用程序可构建。我们可以通过使用 <merge /> 附加虚拟布局来省略它根。因为它没有 child ,所以不会夸大任何观点。
    通用 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>
    
    然后在你的布局中使用它:
    <include
            tools:layout="@layout/your_inflated_layout"
            layout="@layout/lt_merge_empty"
            />
    
    请注意:出于某种原因,tools:layout必须放在 layout 上方属性,否则它不会被渲染。
    编辑:这种方法比 @Sina 更通用是一个原因,通常你会想要显示你动态膨胀的确切布局,所以很明显你不能改变它的 android:visibilitygone .

    关于android - 当布局通常为空且仅以编程方式填充时,我可以显示示例 View 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61909837/

    相关文章:

    android - 禁用 kapt 的增量构建

    android - 设置 android :layout_column = "1" 时 TableLayout 不跳过第 0 列

    android - 如何避免android中相对布局中的重叠 View ?

    android - Android 布局的 Arc Drawable

    整个列表左侧带有小圆圈和线条的 Android ListView ?

    android - 如果再次使用相同的可绘制对象,带有 colorFilter 的自定义 ImageView 将保持相同的过滤器

    java - 持久的 JSON 内容

    Android:在 webvieww 中更改链接颜色

    android - LinearLayout中imageView的大小

    android - Android 的新遗物 : can new relic track http requests made using loopj (android-async-http)?