我想创建一个简单的布局:
我写了这个:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/purple_200">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:background="@color/black" />
</LinearLayout>
但这样做,我没有看到任何黑色的观点出现。我遗漏了什么?
发布于 2022-02-07 07:39:41
有一种叫做ConstraintLayout
的新方法是首选的。您可以使用它的layout_constraintHeight_percent
属性。
示例
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/purple_200"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
输出:
发布于 2022-02-07 07:36:48
你要做的就是添加
android:weightSum="1"
你父母的布局,所以
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
android:background="@color/purple_200">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:background="@color/black" />
</LinearLayout>
我想,在默认情况下,它是1,但它不是,你必须指定它,否则,它是计算为子权重之和,所以在这个例子中,它是0.3。
根据android:权重的定义:
定义最大权重和。如果未指定,则通过添加所有子级的layout_weight来计算和。例如,通过将layout_weight为0.5并将weightSum设置为1.0,可以将单个子节点的可用空间占总可用空间的50%。
发布于 2022-04-30 07:02:17
其他解决方案是androidx.constraintlayout.widget.Guideline.您可以向app:layout_constraintGuide_percent添加指导原则,并且可以在0..1范围内更改constraintLayout变量。你也可以改变方向。
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
https://stackoverflow.com/questions/71021118
复制相似问题