当谈到ConstraintLayout
时,我有更多的概念性问题。我想在我的 ConstraintLayout
中重新使用布局。但我问自己一个问题,ConstraintLayout
旨在避免嵌套布局,而包含布局会降低 ConstraintLayout
性能。避免布局嵌套并同时重用布局以避免代码重复的最佳/良好实践是什么?
最佳答案
您可以使用<merge/>
标签,用于在将一个布局包含在另一个布局中时消除 View 层次结构中的冗余 View 组。
示例:
main.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>
在这种情况下,没有 <merge/>
标签,您将有两个 ConstraintLayout
在布局层次结构中。
引用: https://developer.android.com/training/improving-layouts/reusing-layouts
关于Android约束布局包括另一个布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65826162/