对于我在下面的XML中声明的上述布局,我尝试让view_2
为{{1}时,12dp
的起始边距默认为view_1
}。想知道如何使用GONE
实现它吗?当我遇到约束时,将goneMargin*
上的app:layout_goneMarginStart="12dp"
设置为无效时,就像将小部件平均拉开的相反力(I am referring to this approach of positioning)
view_2
答案 0 :(得分:1)
您将必须以编程方式删除 view_2 上的结束约束。您可能还希望删除 view_2 的底部约束。这是一个示例,其中 view_2 的开始和顶部的 gone 边距为12dp
。
(app:layout_goneMarginStart="12dp"
不起作用,但app:layout_goneMarginLeft="12dp"
起作用。我使用的是 ConstraintLayout 1.1.3 。也许在以后的版本中已解决。)
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private View view1;
int margin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
view1 = findViewById(R.id.view_1);
margin = (int) (12 * getResources().getDisplayMetrics().density);
}
public void onClick(View view) {
ConstraintSet cs = new ConstraintSet();
cs.clone(layout);
if (view1.getVisibility() == View.VISIBLE) {
cs.setVisibility(R.id.view_1, View.GONE);
cs.clear(R.id.view_2, ConstraintSet.END);
cs.clear(R.id.view_2, ConstraintSet.BOTTOM);
} else {
cs.setVisibility(R.id.view_1, View.VISIBLE);
cs.connect(R.id.view_2, ConstraintSet.END, R.id.view_1, ConstraintSet.END);
cs.connect(R.id.view_2, ConstraintSet.BOTTOM, R.id.view_1, ConstraintSet.BOTTOM);
}
cs.applyTo(layout);
}
}
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/layout"
android:layout_width="300dp"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<View
android:id="@+id/view_1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/faded_green"
android:visibility="visible"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/view_2"
android:layout_width="100dp"
android:layout_height="50dp"
android:background="@color/deep_red"
app:layout_constraintBottom_toBottomOf="@+id/view_1"
app:layout_constraintEnd_toEndOf="@+id/view_1"
app:layout_constraintStart_toEndOf="@id/view_1"
app:layout_constraintTop_toTopOf="@id/view_1"
app:layout_goneMarginLeft="12dp"
app:layout_goneMarginTop="12dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Toggle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>