本文介绍了如何向 ConstraintLayout 视图添加不同的权重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的布局中,我有一个 ConstraintLayout 包含两个 TextView 元素.它们目前大小相同,但我希望它们具有 6:4 比率的不同权重.

In my layout, I have a ConstraintLayout containing two TextView elements. They are currently the same size, but I would like them to have different weights with a 6:4 ratio.

如何在我的 ConstraintLayout 中实现?

How can this be achieved in my ConstraintLayout?

推荐答案

In XML

创建一个水平链,然后使用app:layout_constraintHorizo​​ntal_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_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/one"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:background="#caf"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/two"
        app:layout_constraintHorizontal_weight="6"/>

    <TextView
        android:id="@+id/two"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:background="#fac"
        app:layout_constraintLeft_toRightOf="@+id/one"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_weight="4"/>

</android.support.constraint.ConstraintLayout>

创建您的视图并将它们添加到父ConstraintLayout.你需要给他们每个人一个 id 以便一切正常;你可以使用 View.generateViewId() 或者你可以为它们定义一个 id 资源.

Create your views and add them to the parent ConstraintLayout. You will need to give them each an id in order for everything to work; you can use View.generateViewId() or you can define an id resource for them.

// this will be MATCH_CONSTRAINTS width and 48dp height
int height = (int) (getResources().getDisplayMetrics().density * 48);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(0, height);

View left = new View(this);
left.setId(R.id.one);
parent.addView(left, params);

View right = new View(this);
right.setId(R.id.two);
parent.addView(right, params);

然后创建一个 ConstraintSet 对象并创建您的链:

Then create a ConstraintSet object and create your chain:

ConstraintSet set = new ConstraintSet();
set.clone(parent);

int[] chainIds = { R.id.one, R.id.two }; // the ids you set on your views above
float[] weights = { 6, 4 };
set.createHorizontalChain(ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
                          ConstraintSet.PARENT_ID, ConstraintSet.RIGHT,
                          chainIds, weights, ConstraintSet.CHAIN_SPREAD);

set.applyTo(parent);

这篇关于如何向 ConstraintLayout 视图添加不同的权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 13:05