-1
如何在java代码中轻松地集中ConstraintLayout中包含的所有视图?约束ConstraintLayout中的所有视图
使用FrameLayout,我所要做的就是应用中心重力。
我不能使用gui构建器,我的布局需要在运行时生成。
如何在java代码中轻松地集中ConstraintLayout中包含的所有视图?约束ConstraintLayout中的所有视图
使用FrameLayout,我所要做的就是应用中心重力。
我不能使用gui构建器,我的布局需要在运行时生成。
这是我的工作布局:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/first"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#f00"/>
<View
android:id="@+id/second"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#0f0"/>
<View
android:id="@+id/third"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#00f"/>
</android.support.constraint.ConstraintLayout>
这里的,只是显示这个布局是完全愚蠢的活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
为中心的所有意见,我创建了一个ConstraintSet
,使用clone()
对它进行初始化,然后遍历所有的孩子并将它们水平和垂直居中:
ConstraintLayout parent = (ConstraintLayout) findViewById(R.id.parent);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(parent);
for (int i = 0; i < parent.getChildCount(); ++i) {
View child = parent.getChildAt(i);
constraintSet.centerHorizontally(child.getId(), parent.getId());
constraintSet.centerVertically(child.getId(), parent.getId());
}
parent.setConstraintSet(constraintSet);
而现在它看起来像这样:
的可能的复制[?Android的约束布局编程(https://stackoverflow.com/questions/39296627/android-constraint-layout -programmatically) – 0X0nosugar