同样是写 Android 代码,为什么别人的项目结构看起来就是更清晰?差距通常不在编码能力,而在于有没有把三个底层逻辑想明白:分层组织代码、单向数据流、规范化地写布局和存储。这篇文章从布局文件一路讲到数据存储,每个写法都给出能直接跑的示例和踩坑点,你照着对一遍自己的项目,基本就能找到“乱”在哪里。
项目结构乱不乱,差在三个底层逻辑
先说结论:清晰的项目结构,本质上是分层的产物。分层是指把代码按职责切成表现层(UI)、领域层(业务)、数据层(网络和数据库),每层只和相邻层打交道。乱的项目往往所有代码都堆在 Activity 里,布局、网络请求、数据库操作混在一起,改一个功能要翻七八个文件。
第二个逻辑是单向数据流。单向数据流是指数据只有一个方向流动:用户操作 → 触发事件 → 更新唯一的数据源 → UI 自动刷新。它让状态可被预测、可回放,出 bug 时能顺着数据链路排查,而不是在十几个回调里互相打架。
第三个逻辑是命名和目录约定。别人看起来“清爽”,很大程度是因为同类文件放在一起、名字一眼可读。
两种目录组织方式,选哪种?
| 组织方式 | 长什么样 | 适合场景 | 缺点 |
|---|---|---|---|
| 按类型分包 | activity/、fragment/、adapter/ 各一个包 |
入门项目、页面极少 | 功能一多就跨包找代码 |
| 按功能分包 | feature/home/ 里放界面、VM、仓库 |
中大型项目 | 需要自己定好公共模块边界 |
推荐结构长这样:
com.example.shop/
├── feature/
│ ├── home/ HomeScreen.kt、HomeViewModel.kt、HomeRepository.kt
│ └── cart/ 购物车功能的所有文件放一起
├── core/
│ ├── network/ Retrofit 实例、拦截器
│ ├── database/ Room 数据库、DAO
│ └── ui/ 通用组件、BaseActivity
└── MainActivity.kt
按功能分包的核心收益是:改“购物车”功能时,眼睛只盯一个目录。两种方式没有绝对对错,但一个项目里混用两种方式是最糟的——这是很多团队结构越改越乱的直接原因。
布局文件:层级深、重复多是最常见的两个病
打开一个臃肿的布局文件,通常长这样:
<!-- 改前:三层嵌套,层级深、对齐困难、换屏幕尺寸就崩 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="0dp" android:layout_height="wrap_content"
android:layout_weight="1" android:text="用户名" />
<EditText android:layout_width="0dp" android:layout_height="wrap_content"
android:layout_weight="2" />
</LinearLayout>
<Button android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="登录" />
</LinearLayout>
改成 ConstraintLayout 后:
<!-- 改后:平铺一层搞定,约束关系一目了然 -->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvUsername"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="用户名" />
<EditText
android:id="@+id/etUsername"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/tvUsername"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/etUsername"
android:text="登录" />
</androidx.constraintlayout.widget.ConstraintLayout>
经验值:布局嵌套层级尽量控制在 5 层以内,超过基本可以用 ConstraintLayout 或 <include> 平替。踩坑点有两个:一是把“换行”“水平排列”都靠嵌套 LinearLayout 实现,这是层级爆炸的头号原因;二是公共区域(顶部栏、底部卡片)不抽成独立文件,每个页面复制一份,改样式时漏改一处就是线上 bug。
ViewBinding 怎么用,为什么推荐它
ViewBinding 是指一种编译期生成的绑定机制,它为每个布局生成一个 XxxBinding 类,让 findViewById 彻底消失,还带编译期空安全。先在模块的 build.gradle.kts 里打开:
android {
buildFeatures {
viewBinding = true
}
}
使用方式:
class UserActivity : AppCompatActivity() {
private lateinit var binding: ActivityUserBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityUserBinding.inflate(layoutInflater) // 绑定布局+生成类
setContentView(binding.root)
binding.etUsername.setText("") // 直接用控件 ID 当属性,无 findViewById
binding.btnLogin.setOnClickListener { /* ... */ }
}
}
三个高频踩坑点:Fragment 里 inflate 后要记得把 binding.root 作为 onCreateView 的返回值,否则视图不显示;lateinit 在 onDestroyView 里要置空(Fragment 场景),否则视图泄漏;以及别在 ViewModel 里持有 binding——binding 绑定的是视图生命周期,ViewModel 比页面活得久,持有它必然泄漏。
UI 逻辑搬到 ViewModel:一份能直接跑的完整示例
为什么 Activity 不该写业务逻辑?因为配置变更(旋转屏幕)会销毁重建 Activity,逻辑写在页面里,重建后状态就丢了。ViewModel 的职责就是在配置变更时存活,持有并暴露 UI 状态。完整写法如下:
// 1. 状态集中成一个数据类,UI 只认这一个数据源
data class UserUiState(
val loading: Boolean = true,
val name: String = "",
val error: String? = null
)
// 2. ViewModel:私有 MutableStateFlow 负责改,公开只读 StateFlow 负责读
@HiltViewModel
class UserViewModel @Inject constructor(
private val userRepo: UserRepository
) : ViewModel() {
private val _state = MutableStateFlow(UserUiState())
val state: StateFlow<UserUiState> = _state.asStateFlow() // 只读,防止 UI 绕过 VM 改状态
fun refresh() {
viewModelScope.launch { // 3. 协程绑定 VM 生命周期,页面销毁自动取消
_state.update { it.copy(loading = true, error = null) }
userRepo.fetchUser()
.catch { e -> _state.update { it.copy(loading = false, error = e.message ?: "加载失败") } }
.collect { user -> _state.update { it.copy(loading = false, name = user.name) } }
}
}
}
页面侧订阅状态:
class UserActivity : AppCompatActivity() {
private val vm: UserViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...inflate binding...
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) { // 4. 页面不可见时自动停收,恢复时接着收
vm.state.collect { state ->
binding.apply {
progress.isVisible = state.loading
tvName.text = state.name
tvError.isVisible = state.error != null
}
}
}
}
binding.btnRefresh.setOnClickListener { vm.refresh() }
}
}
这段代码逐段解释:状态类让“页面长什么样”变成一个纯数据问题;MutableStateFlow 私有 + StateFlow 公开,保证状态只能通过 VM 的方法修改,单向数据流就是靠这个约定落地的;repeatOnLifecycle 解决了一个经典踩坑——页面在后台时 Flow 还在发数据,订阅者收到通知去更新一个不存在的视图,轻则崩溃重则泄漏。
数据存储:从 SharedPreferences 到 Room 怎么选
存储写法混乱,通常是因为没按数据形态选方案。先给结论:零散的键值配置(登录态、开关项)用 DataStore;结构化、有查询需求的列表用 Room;SharedPreferences 能跑但官方已明确推荐迁移到 DataStore。三者对比:
| 方案 | 数据形态 | 线程安全 | 类型安全 | 典型场景 |
|---|---|---|---|---|
| SharedPreferences | 键值对 | apply() 异步、commit() 同步易阻塞 |
无,键名靠手写字符串 | 老项目维护 |
| DataStore (Preferences) | 键值对 | 全程挂起函数,不阻塞主线程 | 有 PreferencesKey | 登录态、主题开关 |
| Room | 结构化表 | 支持 Flow 自动刷新 | 编译期校验 SQL | 笔记、订单、消息列表 |
DataStore 读写示例
// 1. 扩展函数:给 Context 挂一个命名 DataStore,全项目共享
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefs")
class UserStore @Inject constructor(@ApplicationContext context: Context) {
private val genderKey = stringPreferencesKey("user_gender") // 2. Key 集中定义,杜绝魔法字符串
// 3. 写:挂起函数,天然不在主线程阻塞
suspend fun saveGender(gender: String) {
context.dataStore.edit { settings -> settings[genderKey] = gender }
}
// 4. 读:返回 Flow,订阅即拿到最新值,数据变化自动通知
val genderFlow: Flow<String?> = context.dataStore.data
.map { it[genderKey] }
}
调用侧注意:读写必须放在 lifecycleScope/viewModelScope 里,直接在 onCreate 主线程调用 saveGender 是编译都过不去的强制约束——这正是它比 SharedPreferences 安全的地方。SharedPreferences 的经典踩坑是 commit() 同步写大文件触发 ANR(输入事件约 5 秒无响应就被系统掐断),以及 apply() 之后以为立刻能读到,实际要等异步落盘。
Room 完整示例
// 1. 实体:类即表
@Entity(tableName = "todo")
data class Todo(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val title: String,
val done: Boolean = false,
val createdAt: Long = System.currentTimeMillis()
)
// 2. DAO:接口即 SQL
@Dao
interface TodoDao {
@Query("SELECT * FROM todo ORDER BY createdAt DESC")
fun watchAll(): Flow<List<Todo>> // 返回 Flow:表一变,UI 自动收到新列表
@Insert suspend fun insert(todo: Todo): Long // 返回自增主键
@Query("UPDATE todo SET done = :done WHERE id = :id")
suspend fun setDone(id: Long, done: Boolean)
@Query("DELETE FROM todo WHERE id = :id")
suspend fun delete(id: Long)
}
// 3. 数据库:单例持有
@Database(entities = [Todo::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun todoDao(): TodoDao
}
页面侧一条链路收工:
lifecycleScope.launch {
db.todoDao().watchAll()
.flowWithLifecycle(lifecycle) // 页面不可见时停止收集
.collect { list -> adapter.submitList(list) }
}
Room 的三个必踩坑:一是 DAO 方法不能直接在主线程调用,数据库是磁盘 IO,几百毫秒的卡顿足够触发 ANR,官方直接禁止这种写法,逼你用协程;二是升级表结构必须写 Migration(addMigrations(MIGRATION_1_2)),漏写就 IllegalStateException 崩在启动;三是 watchAll(): Flow 而不是 suspend fun getAll(): List,前者让列表页“表变即刷新”,后者要手动 pull,容易漏。
一张对照表,串起所有写法
| 你现在可能这么写 | 推荐写法 | 背后的逻辑 |
|---|---|---|
| 三层嵌套 LinearLayout | ConstraintLayout + include | 层级 ≤5,维护成本低 |
findViewById 满屏飞 |
ViewBinding | 编译期空安全 |
| 网络/数据库写在 Activity | ViewModel + Repository | 配置变更不丢状态 |
SharedPreferences.putXxx 直接调 |
DataStore 封装类 | 挂起函数防 ANR |
列表数据 List + 手动刷新 |
Room + Flow 自动刷新 | 数据源变,UI 自动变 |
| 所有代码按类型分包 | 按功能分包 | 改功能只看一个目录 |
结构清晰从来不是玄学,而是每个写法背后那条“单一职责”的逻辑被一以贯之。你不需要一次全改——从下一个新功能开始用新写法,把公共部分抽出来,老代码逐步替换,比一次性重写安全得多。
常见问题
项目只有两三个页面,还需要分层和 ViewModel 吗?
需要,但可以简化。分层是习惯问题,小项目按功能分包的成本几乎为零;ViewModel 在两三页的 demo 里收益不明显,但一旦页面要处理异步数据就是刚需。现在省的成本,都是以后重构的利息。
ViewBinding、DataBinding、ButterKnife 选哪个?
选 ViewBinding。它零学习成本、编译期空安全、Google 官方主推。DataBinding 功能强但模板语法学习曲线陡、数据绑定逻辑容易失控;ButterKnife 已停止维护,新项目不要碰。
SharedPreferences 还能用吗?
能跑,但官方文档已明确推荐用 DataStore 替代。它的硬伤是:无类型安全(键名手写字符串)、commit() 同步阻塞易触发 ANR、没有响应式数据流。新代码建议直接上 DataStore,老项目遇到存储相关 bug 时优先考虑迁移。
Room 查询为什么不能写在主线程?
因为 SQLite 是磁盘 IO,查询量一大就是几百毫秒的卡顿,超过约 5 秒系统直接 ANR。Room 编译期就禁止主线程调用 DAO 方法,逼你用 suspend 函数或 Flow——这不是麻烦,是把 ANR 消灭在编译期。
老项目已经很乱,从哪里开始重构最安全?
用“绞杀者模式”:不改老代码,新功能一律按分层写法开发;同时把重复代码抽成公共类放在 core/ 下;等某块老代码被新写法全面替代后,再整块删除。切忌一次性重写——没有测试兜底的重写,失败率极高。