在我的布局中,我有一个ConstraintLayout
包含两个TextView
元素。它们目前大小相同,但我希望它们具有不同的权重,比例为6:4
如何在myConstraintLayout
中实现这一点
在XML中
创建水平链,然后使用app:layout\u constraint\u horizontal\u weight
属性:
<;?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\u width=“匹配父项”
android:layout\u height=“match\u parent”>;
<;文本框
android:id=“@+id/one”
android:layout_width=“0dp”
android:layout\u height=“48dp”
android:background=“#caf”
app:layout\u constraintLeft\u toLeftOf=“parent”
app:layout_constraintRight_toLeftOf=“@+id/two”
app:layout_constraint_weight=“6”/>;
<;文本框
android:id=“@+id/two”
android:layout_width=“0dp”
android:layout\u height=“48dp”
android:background=“#fac”
app:layout_constraintLeft_toRightOf=“@+id/one”
app:layout\u constraintRight\u toRightOf=“parent”
app:layout_constraint_weight=“4”/>;
</android.support.constraint.ConstraintLayout>;
在爪哇
创建视图并将其添加到父视图ConstraintLayout
。你需要给他们每人一个id
,以便一切正常;您可以使用View.generateView()
或为它们定义id
资源
//这将与宽度和48dp高度相匹配
int高度=(int)(getResources().getDisplayMetrics().density*48);
ViewGroup.LayoutParams params=新的ViewGroup.LayoutParams(0,高度);
左视图=新视图(此视图);
左。setId(R.id.one);
parent.addView(左,参数);
视图右侧=新视图(此视图);
对,setId(R.id.two);
parent.addView(右,参数);
然后创建一个ConstraintSet
对象并创建链:
约束集=新的约束集();
set.clone(父级);
int[]chainId={R.id.one,R.id.two};//您在上述视图上设置的ID
float[]权重={6,4};
set.createHorizontalChain(ConstraintSet.PARENT_ID,ConstraintSet.LEFT,
ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,
链ID、权重、约束集、链扩展);
set.applyTo(父级);