首页 > 解决方案 > 如何在中心的视图上锚定一个按钮

问题描述

我正在尝试完成以下操作: 在此处输入图像描述

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

标签: androidkotlinandroid-linearlayoutandroid-constraintlayout

解决方案


我们可以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>

结果

在此处输入图像描述


推荐阅读