随着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的新版本,你现在可以做以下事情:
<Button
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHeight_percent="0.2"
app:layout_constraintWidth_percent="0.65" />
这将限制按钮为父视图高度的20%和宽度的65%。
对于那些可能发现有用的人,你可以使用layout_constraintDimensionRatio在一个ConstraintLayout内的任何子视图中,我们可以定义高度或宽度的比例,其他维度(至少一个必须是0dp宽度或高度)的例子
<ImageView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:src="@drawable/top_image"
app:layout_constraintDimensionRatio="16:9"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
在这种情况下,纵横比是16:9 app:layout_constraintDimensionRatio=“16:9”你可以在这里找到更多信息
简单地,在指导标签中替换
app:layout_constraintGuide_begin="291dp"
with
app:layout_constraintGuide_percent="0.7"
其中0.7表示70%。
另外,如果您现在尝试拖动指导方针,拖动的值现在将以%age显示。
使用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和以下版本)
约束布局1.0使一个视图占据屏幕的百分比需要制定两个指南。在约束布局1.1中,通过允许您轻松地将任何视图限制为一个百分比的宽度或高度,它变得更加简单。
这不是很棒吗?所有视图都支持layout_constraintWidth_percent和layout_constraintHeight_percent属性。这将导致约束固定在可用空间的一个百分比上。因此,让按钮或TextView扩展以填充屏幕的百分比可以用几行XML完成。
例如,如果你想设置按钮的宽度为屏幕的70%,你可以这样做:
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_constraintWidth_percent="0.7" />
请注意,你将不得不把尺寸应该使用百分比到0dp,因为我们已经指定android:layout_width到0dp上面。
同样,如果你想设置按钮的高度为屏幕的20%,你可以这样做:
<Button
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_constraintHeight_percent="0.2" />
看!我们已经指定android:layout_height为0dp这次,因为我们想按钮使用高度百分比。
推荐文章
- Android是否保留。apk文件?如果有,在哪里?
- 在Android 5棒棒糖中,通知栏图标变成白色
- 从URI获取真实路径,Android奇巧新的存储访问框架
- 如何检查JSON键是否存在?
- ImageView -有高度匹配宽度?
- 如何确定在android文件的MIME类型?
- 这是在Android中获取用户位置的好方法
- Android从左到右幻灯片动画
- 如何检索视图的维度?
- 如何改变菜单项的文本颜色在安卓?
- Android选择器和文本颜色
- 视图绑定-我如何获得包含布局的绑定?
- 在Android Studio中改变矢量资产的填充颜色
- 在构建中编写注释的语法是什么?gradle文件?
- 如何以编程方式添加按钮色调