RelativeLayout实现居中偏下x距离引发的小问题

        UE想实现一个简单的效果,某个控件在屏幕水平线下方50dp。由于受限于项目历史布局(RelativeLayout)和一套动态化设置控件位置的方案,竟然遇到了一点问题。(在这里还是喊一声:ConstraintLayout最香)。

        我们都知道,RelativeLayout没有gravity这个属性,但是想实现居中很简单,有如下属性:

        android:layout_centerHorizontal="true"  //水平居中
        android:layout_centerInParent="true"    //水平和垂直都居中
        android:layout_centerVertical="true"    //垂直居中

        假如要实现控件垂直居中偏下50dp,那要如何实现呢?例如我想实现如下布局,控件距离屏幕中线50dp:

         一开始,想都没想,直接代码里设置centerVertical和MarginTop:50,结果竟然跟预想的不一样,设置了垂直居中后,再设置垂直方向的margin是不管用的。同样的,设置了水平居中后再设置水平的margin也是不行的,设置了水平和垂直都居中后,那么设置任何方向的margin都不再有效。在此我们先不去深挖为何不生效,先看看如何基于RelativeLayout实现该效果。

        答案也比较简单:可以设置居中后,给View设置一个偏移量。注意:translationY是控件位置的偏移量,是相对于中点来说。如果需要顶部距离中线50dp,则应该设置translationY:50+View.height/2

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:src="@color/black"
        android:translationY="50dp" />

</RelativeLayout>

    补充下约束布局的实现:

<?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"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@color/black"
        android:layout_marginTop="50dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个玩游戏的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值