You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android中如何设计重叠元素?附已实现界面的逻辑与代码

我刚搞定了这个类似目标界面的实现,来跟大家唠唠我的实现逻辑和代码:

界面布局层级逻辑

整个界面的布局结构是这样的:

  • 根容器:FrameLayout(用来实现多布局层叠效果)
    • 第一层:横向LinearLayout,用来承载两个平分宽度的按钮
      • 紫色按钮:设置layout_width=1,占满对应权重的宽度
      • 蓝色按钮:同样设置layout_width=1,和紫色按钮平分父布局宽度
    • 第二层:LinearLayout,通过layout_gravity=center让它居中显示,里面放带文本的核心按钮
完整源代码
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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">

    <!-- 平分宽度的按钮容器 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="1"
            android:layout_height="wrap_content"
            android:background="@color/purple_500"
            android:textColor="@android:color/white"
            android:text="紫色按钮" />

        <Button
            android:layout_width="1"
            android:layout_height="wrap_content"
            android:background="@color/blue_500"
            android:textColor="@android:color/white"
            android:text="蓝色按钮" />
    </LinearLayout>

    <!-- 居中显示的按钮容器 -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="核心操作按钮" />
    </LinearLayout>
</FrameLayout>

小提示:如果想要按钮平分宽度的效果更稳定,建议把按钮的layout_width设为0dp,再添加android:layout_weight="1",这样在不同分辨率的设备上适配性会更好哦~

内容的提问来源于stack exchange,提问作者Sachin Jain

火山引擎 最新活动