Android约束布局包括另一个布局

标签 android android-layout kotlin android-constraintlayout

当谈到ConstraintLayout时,我有更多的概念性问题。我想在我的 ConstraintLayout 中重新使用布局。但我问自己一个问题,ConstraintLayout 旨在避免嵌套布局,而包含布局会降低 ConstraintLayout 性能。避免布局嵌套并同时重用布局以避免代码重复的最佳/良好实践是什么?

最佳答案

您可以使用<merge/>标签,用于在将一个布局包含在另一个布局中时消除 View 层次结构中的冗余 View 组。

示例:

ma​​in.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <include layout="@layout/include_layout"/>

</androidx.constraintlayout.widget.ConstraintLayout>

include_layout.xml

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

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
</merge>

结果: enter image description here

在这种情况下,没有 <merge/>标签,您将有两个 ConstraintLayout在布局层次结构中。

enter image description here

引用: https://developer.android.com/training/improving-layouts/reusing-layouts

关于Android约束布局包括另一个布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65826162/

相关文章:

java - 更改x轴的日期时间格式?

java - 无法在 Windows 上运行 Roboletric : java. lang.NoSuchMethodException : android. os.Looper.<init>(boolean)

android - 像 any.do 一样的弹出窗口

android - 我可以引用任何其他 xml 来设置动态布局的样式吗

unit-testing - 协程测试失败, "This job has not completed yet"

unit-testing - Mockito never() 不与 andThen rxjava2 一起使用

java - 当我点击一个按钮时,我只想激活它周围的按钮。这怎么可能?

android - 服务启动的 Intent 过滤器

android - 资源和布局方向仅在 Android 8.0 及更高版本上呈现不正确

android-studio - 切换时如何在 Kotlins 中使用多行?