将布局文件包含到约束布局中,而不会影响性能或Android Studio预览

时间:2020-01-23 09:17:54

标签: android android-constraintlayout

我有一个巨大的布局文件,其中包含一个平面约束布局。

我有android.support.constraint.Group个相同的元素。我想将它们移到一个单独的文件中,然后像<include layout="@layout/selection_group"/>

那样包含它们

我面临的问题是文件selection_group.xml中的组在Android Studio中无法正确预览。有没有一种方法可以使Android Studio直接在文件中预览此图像,或以其他方式包含它们?

selection_group.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.constraint.Group
        android:id="@+id/top_bar_config_one_background_group"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/top_bar_background_with_border_fx"
        android:clickable="true"
        app:constraint_referenced_ids="top_bar_config_one,top_bar_tooth_one"
        app:layout_constraintBottom_toBottomOf="@+id/top_bar_container_background"
        app:layout_constraintLeft_toLeftOf="@+id/top_bar_container_background"
        app:layout_constraintRight_toLeftOf="@+id/top_bar_config_two"
        app:layout_constraintTop_toTopOf="@+id/top_bar_container_background" />

    <ImageView
        android:id="@+id/top_bar_config_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:scaleType="center"
        android:src="@drawable/ic_height_over_sea_100x26"
        app:layout_constraintBottom_toTopOf="@+id/top_bar_tooth_one"
        app:layout_constraintLeft_toLeftOf="@+id/top_bar_container_background"
        app:layout_constraintRight_toLeftOf="@+id/top_bar_config_two"
        app:layout_constraintTop_toTopOf="@+id/top_bar_config_one_background_group" />

    <ImageView
        android:id="@+id/top_bar_tooth_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@drawable/ic_tooth_auto_40x40"
        app:layout_constraintBottom_toBottomOf="@+id/top_bar_config_one_background_group"
        app:layout_constraintLeft_toLeftOf="@+id/top_bar_container_background"
        app:layout_constraintRight_toLeftOf="@+id/top_bar_config_two" />
    <?xml version="1.0" encoding="utf-8"?>
</layout>

我不想将多个约束布局嵌套在一起。我认为<layout>中的根selection_group.xml视图已经过优化,并且不影响性能吗?我的目标是减少冗余代码而不影响性能

2 个答案:

答案 0 :(得分:1)

尝试在包含的布局中添加 merge 标记:

<layout>
    <merge>
    <group>
    ... etc. ...
    </merge>
</layout>

答案 1 :(得分:1)

为了准备好包含该布局文件,您需要将<layout>替换为<merge>

如果您需要在布局中使用数据绑定,则需要首先使用<layout,而不要在布局文件的顶部使用<merge>标签

我要在您要包含的内部布局中进行适当的预览-在顶层添加到合并标签中:

tools:parentTag =“ ContraintLayout”

类似这样的东西:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="androidx.constraintlayout.widget.ConstraintLayout">