kotlin - 在 Kotlin Anko 中使用 ConstraintLayout
问题描述
我正在使用Anko 中的 ContraintLayout 支持,遇到了一个问题,我无法让最简单的示例正常工作。
我在约束布局中的屏幕顶部水平放置了两个按钮,它们充当链,使它们水平居中。
我做的第一件事是使用良好的旧 xml 布局和 Android Studio,这样我就可以查看生成的代码。
这是我的非 Anko xml 布局
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First"
app:layout_constraintEnd_toStartOf="@+id/button5"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintStart_toStartOf="parent"
/>
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/button4"
/>
这会产生正确的布局,如下所示
现在下面是我认为应该是产生相同结果的等效 Kotlin Anko 代码。
constraintLayout {
id = R.id.constraintRoot
val first : Button = button("First"){
id = R.id.firstButton
width = wrapContent
height = wrapContent
}.lparams{
//topToTop = ConstraintSet.PARENT_ID
startToStart = PARENT_ID
endToStart = R.id.secondButton
horizontalChainStyle = spread
editorAbsoluteY = 16
horizontalBias = 0.5f
}
val second : Button = button("Second"){
id = R.id.secondButton
width = wrapContent
height = wrapContent
}.lparams{
startToEnd = R.id.firstButton
endToEnd = PARENT_ID
editorAbsoluteY = 16
horizontalBias = 0.5f
}
}
但是由于某种原因,这会产生以下结果。
如您所见,按钮在视图内没有均匀分布和水平居中。
有什么我遗漏的,或者 Anko 的 ConstraintLayout 还没有准备好用于生产吗?
谢谢!
解决方案
所以我最终使用了一个指南来给我想要的结果。
constraintLayout {
id = R.id.constraintRoot
val first : Button = button("First"){
id = R.id.firstButton
width = wrapContent
height = wrapContent
}.lparams{
endToStart = R.id.verticalGuideline
startToStart = ConstraintSet.PARENT_ID
}
val gl : Guideline = guideline {
id = R.id.verticalGuideline
}.lparams {
orientation = ConstraintLayout.LayoutParams.VERTICAL
guidePercent = 0.5f
}
val second : Button = button("Second"){
id = R.id.secondButton
width = wrapContent
height = wrapContent
}.lparams{
startToEnd = R.id.verticalGuideline
endToEnd = ConstraintSet.PARENT_ID
}
}
推荐阅读
- javascript - JavaScript 中的 SUMIF()?
- c - 解析 C 声明
- android - 在RxAndroid(Observable)中将订阅添加到disposable后,控制流结束而不调用subscribe..!
- angular - Datepicker Angular Material 过滤器验证
- java - 如何使用 Hibernate 的 CriteriaBuilder 构建 select count(*) 和 group by SQL 查询?
- javascript - 是否有在保留对象的同时解构对象属性的快捷方式?
- apache-nifi - Apache NiFi评估jsonpath处理器:连接2个属性的JSONPath表达式
- android - 修复了可见的标签/点 TabLayout android
- java - 从笛卡尔积中获取不同记录的算法
- flutter - Stepper 中的图标太大