一、前言:
1、原因:
我们在用约束布局的时候,有时候写layout_constraintHorizontal_weight属性没有任何效果,这是因为我们没有把控件的约束边界写好。
效果如图:
展示图1.png 展示图2.png2、解决方案:
下面我们以展示图2为例子进行说明:
我们现在有两个控件tv1,tv2和tv3,三个控件要进行横向平分,现在要让他们平分空间必须在他们之间建立链条,怎么建立链条呢,其实就是要让他们互相关联,每个控件都要设置如下属性:
app:layout_constraintLeft_to...
app:layout_constraintRight_to...
就建立了链条,(我中有你,你中有我)。 然后再设置
layout_constraintHorizontal_weight=“1”
这样就各占一半当前空间。
记住一定要互相关联,每个控件都要有相对于其它控件左右的属性。
示图如下:
展示图2.png代码如下:
<?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">
<TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_height="200dp"
android:background="#ff0000"
android:gravity="center"
android:text="布局一"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/tv2"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/tv2"
android:layout_width="0dp"
android:layout_height="200dp"
android:background="#00ff00"
android:gravity="center"
android:text="布局二"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintLeft_toRightOf="@+id/tv1"
app:layout_constraintRight_toLeftOf="@+id/tv3"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/tv3"
android:layout_width="0dp"
android:layout_height="200dp"
android:background="#0000ff"
android:gravity="center"
android:text="布局三"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintLeft_toRightOf="@+id/tv2"
app:layout_constraintRight_toRightOf="parent"
tools:ignore="MissingConstraints" />
<androidx.constraintlayout.widget.Group
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
app:constraint_referenced_ids="tv2"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
说明:如若只有三个控件显示Group可以不写,Group中的constraint_referenced_ids可以指定控件的显示和隐藏。
网友评论