随着Android Studio 2.2的预览1,谷歌在其支持库中发布了一个新的布局:ConstraintLayout。使用ConstraintLayout,在Android Studio中更容易使用设计工具,但我没有找到一种方法来使用相对大小(百分比或“权重”,如线性布局)。是否有一种基于百分比定义约束的方法?例如,让一个视图占屏幕的40%,在视图之间创建20%的空白,将一个视图的宽度设置为另一个视图宽度的50% ?
当前回答
使用指南,您可以将定位更改为基于百分比
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5"/>
你也可以用这种方式
android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent="0.4"
其他回答
目前有几种方法可以做到这一点。
一种是创建导线(右键单击设计区域,然后单击添加垂直/水平导线)。然后,您可以单击指导方针的“标题”来更改定位为基于百分比。最后,您可以将视图约束为指导方针。
另一种方法是使用偏差(百分比)定位视图,然后将其他视图锚定在该视图上。
也就是说,我们一直在考虑如何提供基于百分比的维度。我不能做任何保证,但这是我们想补充的。
使用ConstraintLayout v1.1.2,维度应该设置为0dp,然后将layout_constraintWidth_percent或layout_constraintHeight_percent属性设置为0到1之间的值,例如:
<!-- 50% width centered Button -->
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintWidth_percent=".5" />
(你不需要设置app:layout_constraintWidth_default="percent"或app:layout_constraintHeight_default="percent"与ConstraintLayout 1.1.2和以下版本)
这里有一个快速的参考可能是有用的。
视图的放置
使用app:layout_constraintGuide_percent的指导原则,如下所示:
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5"/>
然后你可以使用这个指导原则作为其他视图的锚点。
or
使用app:layout_constraintHorizontal_bias和/或app:layout_constraintVertical_bias在可用空间允许的情况下修改视图位置
<Button
...
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.25"
...
/>
视图大小
另一个基于百分比的值是元素的高度和/或宽度,使用app:layout_constraintHeight_percent和/或app:layout_constraintWidth_percent:
<Button
...
android:layout_width="0dp"
app:layout_constraintWidth_percent="0.5"
...
/>
一个有用的补充是设置另一个维度相对于第一个维度,例如-根据宽度按比例设置高度:
app:layout_constraintDimensionRatio="1:1"
简单地,在指导标签中替换
app:layout_constraintGuide_begin="291dp"
with
app:layout_constraintGuide_percent="0.7"
其中0.7表示70%。
另外,如果您现在尝试拖动指导方针,拖动的值现在将以%age显示。
使用指南,您可以将定位更改为基于百分比
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5"/>
你也可以用这种方式
android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent="0.4"
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。