解决方案:
要在布局中附加一个xml文件,您可以使用<include>
标记。
重用布局特别强大,因为它允许您创建可重用的复杂布局。例如,带有是/否按钮面板或自定义进度条和说明文本的布局。 更多信息
您可以使用ConstraintLayout
来实现问题中所示的功能。当然,也有使用旧版<LinearLayout>
和称为权重的内容的解决方案,但正如警告所说,使用权重会影响性能。
为什么使用权重会影响性能?
布局权重需要对小部件进行两次测量。当具有非零权重的LinearLayout嵌套在具有非零权重的另一个LinearLayout中时,测量次数呈指数增长。
因此,让我们使用<ConstraintLayout>
来解决问题。
假设我们有一个名为my_activity_layout.xml
的布局文件,并使用以下代码来实现我们想要的效果:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<SurfaceView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.67" />
<include
android:id="@+id/news_title"
layout="@layout/my_activity_layout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>
Guideline
可以帮助我们获得屏幕的2/3即66.666 ~ 67%,然后您可以使用<include>
标签在活动中约束您的SurfaceView
和布局。<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"/>
<include layout="my_activity_layout.xml"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>