首页 > 解决方案 > 无法在 LinearLayout 中居中 PercentRelativeLayout

问题描述

我有一个片段,它有一个方形相机(宽度和高度都等于屏幕宽度),在 PercentRelativeLayout 中表示为 FrameLayout。在这个摄像头下面是一个 ImageView,它在单击时拍摄照片。

我想将方形相机垂直居中(因为它已经覆盖了屏幕宽度),然后将 ImageView 居中在它下方的剩余空间中。这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/llCameraFragment"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000">

    <android.support.percent.PercentRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <FrameLayout
            android:id="@+id/tvCamera"
            app:layout_widthPercent="100%"
            app:layout_aspectRatio="100%" />
    </android.support.percent.PercentRelativeLayout>

    <LinearLayout
        android:id="@+id/llBelowCamera"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

    <ImageView
        android:id="@+id/ivCaptureImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/camerashutter" />
    </LinearLayout>

</LinearLayout>

问题是相机视图(PercentRelativeLayout)总是从屏幕的最顶部开始。我已经尝试在 PercentRelativeLayout 中使用layout_gravity而不是gravity,并且还尝试将其包裹在 LinearLayout 周围,并将重力设置为 center / center_vertical。

知道有什么问题吗?感谢任何努力:)

标签: javaandroidxmlfrontend

解决方案


这是您尝试使用ConstraintLayout. 正如你所看到的,它更容易也更有效。

<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"
  android:orientation="vertical">

  <FrameLayout
    android:id="@+id/tvCamera"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintDimensionRatio="H, 1:1"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

  <ImageView
    android:id="@+id/ivCaptureImage"
    android:layout_width="100dp"
    android:layout_height="100dp"
    app:layout_constraintTop_toBottomOf="@id/tvCamera"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    />
</android.support.constraint.ConstraintLayout>

让我知道您是否最终使用它以及是否需要更多帮助


推荐阅读