我可以想出两种方法。一种只使用XML,但不太灵活,第二种需要对代码进行一些更改并对
Views
. 请注意,这两种方法都只在颜色段的可见性设置为
GONE
,作为视图
INVISIBLE
仍然专注的空间。
-
我们将两个视图的宽度百分比设置为50%。当颜色
段是
跑了
由于
水平偏差。如果设置了
这些视图的页边距,因为它们的固定大小为
布局的可用宽度。
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/color"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Color"
app:layout_constraintWidth_percent="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0"/>
<TextView
android:id="@+id/size"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Size"
app:layout_constraintWidth_percent="0.5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/color"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0"/>
</android.support.constraint.ConstraintLayout>
-
我们将这两个视图放在一个加权链中,但也添加了一个
Space
帮手
在“颜色”时作为剩余空间的填充
视图为
跑了
. 可见的视图都具有以下权重:
0.5
,每个占可用空间的一半。这个
空间
助手的重量为
0
因此不可见。
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout">
<TextView
android:id="@+id/color"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Color"
app:layout_constraintEnd_toStartOf="@id/size"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintHorizontal_weight="0.5"/>
<TextView
android:id="@+id/size"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Size"
app:layout_constraintEnd_toStartOf="@id/space"
app:layout_constraintStart_toEndOf="@id/color"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="0.5"/>
<Space
android:id="@+id/space"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/size"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="0"/>
</android.support.constraint.ConstraintLayout>
现在当你需要隐藏你的颜色片段时,你可以做些什么
这样地:
ConstraintSet cs = new ConstraintSet();
ConstraintLayout layout = findViewById(R.id.layout);
Space space = findViewById(R.id.space);
TextView color = findViewById(R.id.color);
cs.clone(layout);
cs.setHorizontalWeight(space.getId(), 0.5f);
cs.applyTo(layout);
color.setVisibility(View.GONE);
这将使颜色段消失,但大小段
将向左滑动,因为约束保持均匀
然后视图的可见性设置为
跑了
. 这个
空间
有它的
重量设置为
零点五
将占据空间的右半。