一、RelativeLayout介绍
RelativeLayout是Android提供的一种布局方式,其布局的方式比较灵活。RelativeLayout是按照控件间的相对位置进行布局,方便适应各种复杂的布局要求。通过使用不同的定位方式,我们可以让控件的位置在左上角、中间、右下角等任意位置。除此之外,RelativeLayout还可以实现布局的高度自适应,可以为我们的开发带来很多方便。
二、使用RelativeLayout实现布局
在RelativeLayout中,我们可以使用很多种方式来定位控件的位置。比如我们可以使用android:layout_alignParentTop、android:layout_alignParentBottom等属性来定位控件在父布局的顶部或底部,还可以使用android:layout_above、android:layout_below等属性来定位控件在其他控件的上面或下面。
举个例子,如果我们想要实现一个头像在左边、名称在右边的布局,可以这样实现:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/avatar"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="张三"
android:textSize="18sp"
android:layout_toRightOf="@id/avatar"
android:layout_alignBaseline="@id/avatar" />
</RelativeLayout>
上述代码中,头像控件的android:layout_alignParentLeft=”true”属性和名称控件的android:layout_toRightOf=”@id/avatar”属性分别让它们在左边和右边布局,而android:layout_alignBaseline=”@id/avatar”属性则使得它们的底部对齐。在这个例子中,我们没有直接指定布局的高度,而是使用了android:layout_height=”wrap_content”属性,这样布局就可以根据内部控件的高度自适应。
三、实现布局高度自适应
在上述例子中,我们已经使用了android:layout_height=”wrap_content”属性来实现布局的高度自适应了。除此之外,RelativeLayout还提供了另外一个实现布局高度自适应的属性:android:layout_alignParentBottom
如果我们想要实现一个类似微信聊天的布局,即发送消息在右边,接收消息在左边,我们可以这样实现:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFF"
android:padding="10dp"
android:text="你好,我是小明"
android:textSize="16sp"
android:layout_marginRight="80dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" />
<LinearLayout
android:id="@+id/avater_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true">
<ImageView
android:id="@+id/avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/avatar" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="小明"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
上述代码中,我们使用了android:layout_alignParentBottom=”true”属性,使得TextView的底部与其父布局的底部对齐。在这种布局中,如果发送消息的TextView高度为100dp,而接收消息的TextView高度为200dp,RelativeLayout的布局高度会自适应为200dp。
四、总结
RelativeLayout是一种比较灵活的布局方式,可以通过各种方式来定位控件的位置。通过使用android:layout_height=”wrap_content”和android:layout_alignParentBottom=”true”属性,我们可以很方便地实现布局的高度自适应。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/193222.html
微信扫一扫
支付宝扫一扫