java - 以编程方式设置百分比宽度约束布局Android
问题描述
对于 Android 中的约束布局 v1.1.x,我们可以将高度和宽度设置为百分比。同样,需要在 Android 中以编程方式将视图宽度和高度设置为百分比:例如,这段代码是用 xml 编写的,用于一些约束布局:
<!-- the widget will take 40% of the available space -->
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent="0.4"
它运行时的java代码是什么?
解决方案
您需要使用 ConstraintSet -参考
此类允许您以编程方式定义一组要与 ConstraintLayout 一起使用的约束。它允许您创建和保存约束,并将它们应用到现有的 ConstraintLayout。ConstraintsSet 可以通过多种方式创建:
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);
您可以在此集合上调用那些高度宽度百分比方法
并像这样将这些约束应用于您的约束布局
set.applyTo(mConstraintLayout);
推荐阅读
- php - 来自数据库的图像以调整大小并存储在服务器上
- php - 如何在 Ubuntu 或 Debian 服务器上永久运行我的 php 聊天套接字应用程序?
- ruby-on-rails - 带有远程处理错误消息的 Rails4 表单
- hive - 使用 hive 函数对数据进行排序
- android - 我的 PagerAdapter 不显示任何内容
- c++ - “*const char *”类型的值不能分配给“char *”类型的实体
- ansible - 在 Vagrant 中构建完所有虚拟机后,Anisble 会在 playbook 中运行两次
- php - 如何打开已经在内存中的 SQLite3 文件,而无需在 PHP 中接触磁盘?
- android - 简单的导航抽屉
- angular - 隐藏在 Angular 2 版本 6 中不起作用