首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Android线性/相对布局 - 如何在中间"自动调整大小"对象(3个对象)

在Android开发中,相对布局(RelativeLayout)和线性布局(LinearLayout)是常见的布局方式。要在中间"自动调整大小"的对象(例如3个对象),可以使用以下方法:

  1. 使用相对布局(RelativeLayout):

在相对布局中,可以使用android:layout_centerInParent属性将对象放置在父布局的中心,并使用android:layout_toLeftOfandroid:layout_toRightOf属性将对象放置在中心对象的左侧和右侧。

示例代码:

代码语言:xml<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">

    <View
        android:id="@+id/center_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:background="@color/colorPrimary" />

    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_toLeftOf="@id/center_view"
        android:background="@color/colorAccent" />

    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_toRightOf="@id/center_view"
        android:background="@color/colorPrimaryDark" />

</RelativeLayout>
  1. 使用线性布局(LinearLayout):

在线性布局中,可以使用android:layout_weight属性将对象放置在中心,并使用android:layout_gravity属性将对象放置在中心对象的左侧和右侧。

示例代码:

代码语言:xml<LinearLayout 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"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <View
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:background="@color/colorAccent" />

    <View
        android:id="@+id/center_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:background="@color/colorPrimary" />

    <View
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:background="@color/colorPrimaryDark" />

</LinearLayout>

这两种方法都可以实现在中间"自动调整大小"的对象(3个对象)。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券