-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