随着Android Studio 2.2的预览1,谷歌在其支持库中发布了一个新的布局:ConstraintLayout。使用ConstraintLayout,在Android Studio中更容易使用设计工具,但我没有找到一种方法来使用相对大小(百分比或“权重”,如线性布局)。是否有一种基于百分比定义约束的方法?例如,让一个视图占屏幕的40%,在视图之间创建20%的空白,将一个视图的宽度设置为另一个视图宽度的50% ?
当前回答
随着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%。
其他回答
简单地,在指导标签中替换
app:layout_constraintGuide_begin="291dp"
with
app:layout_constraintGuide_percent="0.7"
其中0.7表示70%。
另外,如果您现在尝试拖动指导方针,拖动的值现在将以%age显示。
在“ConstraintLayout1.1.0-beta1”中,你可以使用百分比来定义宽度和高度。
android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent=".4"
这将定义宽度为屏幕宽度的40%。 这和百分比指导方针的组合允许您创建任何基于百分比的布局。
我知道这不是OP最初要求的,但在这种情况下,当我有类似的问题时,这帮助了我很多。添加这为人们希望改变布局窗口大小(我经常使用),通过代码。将此添加到您的onCreate活动的问题。(改为80%)
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width * 0.8), (int)(height * 0.8));
试试这段代码。你可以用app:layout_constraintHeight_percent和app:layout_constraintWidth_percent来改变高度和宽度百分比。
<?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">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF00FF"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent=".6"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".4"></LinearLayout>
</android.support.constraint.ConstraintLayout>
Gradle:
dependencies {
...
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
如何使用指南
公认的答案是有点不清楚如何使用指导方针和什么是“头”。
步骤
首先添加一个指南。
选择指导方针或移动它一点,使约束可见。
然后点击圆(“标题”),直到它变成一个百分比。然后你可以把这个百分比拖到50%或任何你想要的。
之后,你可以将你的视图约束到guideguide,使其成为父视图的一部分(在视图上使用match_constraint)。
推荐文章
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角