You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中实现复杂自定义View应选用哪种布局?

实现方案

布局选择

优先选用ConstraintLayout,该布局支持控件叠加、相对定位,无需多层嵌套即可实现标题压在边框上沿的效果,也可选用FrameLayout实现同类叠加需求。

完整XML代码

<?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"
    android:layout_width="400dp"
    android:layout_height="200dp"
    android:layout_gravity="center_horizontal">

    <!-- 背景黑框,沿用你自定义的box drawable资源 -->
    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="8dp"
        android:background="@drawable/box"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- 悬浮在边框上沿的标题 -->
    <TextView
        android:id="@+id/titleTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:paddingHorizontal="4dp"
        android:text="Sample"
        android:textSize="20sp"
        app:layout_constraintMarginStart="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- 可在此处添加框内其他内容控件,按需求设置约束即可 -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="内部展示内容"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

如果开发环境提示找不到ConstraintLayout,在模块级build.gradle的dependencies块中添加依赖即可:

implementation 'androidx.constraintlayout:constraintlayout:2.1.4'

实现逻辑说明

  • 背景框设置了8dp的顶部margin,为标题留出重叠空间
  • 标题设置了和页面背景一致的白色背景,刚好遮盖住边框的上沿部分,实现标题嵌入边框的视觉效果
  • 所有子控件都可以通过约束调整位置,后续要新增内容不需要修改布局嵌套结构

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:36:07