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>