如何在中心视图上锚定按钮

问题描述 投票:0回答:1

我正在尝试完成以下任务:enter image description here

灰色部分是活动的背景,白色部分是水平的LinearLayout。我想创建与LinearLayout顶部边框重叠的微调框,但我所能做的就是将其放在布局内或顶部。有没有办法做到这一点?或解决方法?

android kotlin android-linearlayout android-constraintlayout
1个回答
0
投票

我们可以使用ConstraintLayout。我们需要使用两个属性的组合

layout_constraintTop_toBottomOf
layout_constraintBottom_toBottomOf

这将使Button或任何其他View居中

示例

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<View
    android:id="@+id/topView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@android:color/holo_orange_dark"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    android:orientation="horizontal" />

<View
    android:id="@+id/bottomView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    app:layout_constraintTop_toBottomOf="@id/topView"
    android:background="@android:color/holo_green_light"
    android:orientation="horizontal" />

<com.google.android.material.button.MaterialButton
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@id/topView" // this 
    app:layout_constraintBottom_toBottomOf="@id/topView" // and this is important, it aligns the view to the top view
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.