以编程方式设置Android的width约束布局百分比 [英] set percent width constraintlayout Android programmatically

查看:1822
本文介绍了以编程方式设置Android的width约束布局百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Android中的约束布局v1.1.x,我们可以将高度和宽度设置为百分比. 同样,需要以编程方式在Android中将视图的宽度和高度设置为百分比: 例如,此代码是用xml编写的,用于一些约束布局:

For constraint layout v1.1.x in Android we can set height and width as percentage. Similarly, need to set view width and height as percent in Android programmatically: for example, this code is written in xml for some constraint layout:

<!-- the widget will take 40% of the available space -->
    app:layout_constraintWidth_default="percent"
    app:layout_constraintWidth_percent="0.4"

在运行时执行的Java代码是什么?

what will be its java code for doing it runtime?

推荐答案

您需要使用ConstraintSet-参考

You need to use ConstraintSet - Reference

通过此类,您可以以编程方式定义一组约束,以与 ConstraintLayout 一起使用.它使您可以创建和保存约束,并将其应用于现有的ConstraintLayout. ConstraintsSet可以通过多种方式创建:

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways:

mConstraintLayout = (ConstraintLayout) findViewById(R.id.myconstraint_layout)

ConstraintSet set = new ConstraintSet();

// Add constrains - Here R.id.myconstraint_layout is the Id of your constraint layout
set.constrainPercentHeight(R.id.myconstraint_layout, 0.4);
set.constrainPercentWidth(R.id.myconstraint_layout, 0.4);

// Apply the changes - mConstraintLayout is reference to the desired view
set.applyTo(mConstraintLayout); 

您可以在此集合上调用那些高度宽度百分比方法

You can call those height width percentage methods on this set

  • constrainPercentHeight(int viewId, float percent)
  • constrainPercentWidth(int viewId, float percent)

像这样将这些约束应用于您的约束布局

And apply those constraints to your Constraint Layout like this

set.applyTo(mConstraintLayout); 

这篇关于以编程方式设置Android的width约束布局百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆