常见方案对比
方案适用场景特点include 布局静态拆分,不需要复用简单,布局复用自定义 ViewUI+逻辑封装,可复用封装度高Fragment动态加载,独立生命周期灵活,但复杂RecyclerView列表,每行算一个组件最常用实际建议
- 复杂页面(如患者详情页)
- ├── 患者基本信息卡片 → include 或 自定义 CardView
- ├── 医嘱列表区域 → RecyclerView + Adapter
- ├── 执行记录区域 → RecyclerView + Adapter
- ├── 备注信息区域 → include
- └── 底部操作栏<?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:padding="16dp">
-
- <com.xx.xxxxx.widget.CaptchaView
- android:id="@+id/captchaView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout> → include
复制代码 不是越拆越好:
- 2-3 个简单区域 → 直接写一个 XML
- 重复使用的区域 → 抽成 include 或自定义 View
- 需要独立管理生命周期 → Fragment
- 列表类型 → RecyclerView
多组件编码示例
示例场景:登录页拆分
- LoginActivity
- ├── 顶部 Logo 区域(LogoView)
- ├── 账号输入区域(AccountInputView)
- ├── 验证码区域(CaptchaView)
- └── 登录按钮区域(LoginButtonView)
复制代码 方案 A:include + ViewBinding(简单拆分)
activity_login.xmlLoginActivity.java方案 B:自定义 View(封装业务逻辑)
适合复杂且可复用的组件,比如验证码组件:
CaptchaView.java(自定义组件)activity_login.xml(使用自定义组件)- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:padding="16dp">
-
- <com.xx.xxxxx.widget.CaptchaView
- android:id="@+id/captchaView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
复制代码 LoginActivity.java(更简洁)方案 C:Fragment(动态拆分)
适合需要独立管理生命周期的场景:总结
场景应用复杂页面拆分
多组件编码
- 简单用 include
- 复杂用自定义 View
- 动态加载用 Fragment
实际项目中:
- 登录页这种简单页面 → 直接写一个 XML + Activity
- 详情页 → include 抽公共部分
- 列表页 → RecyclerView + 多类型 ViewHolder
- Tab 切换 → Fragment
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |