光影流年-精彩电影分享网场记板 · 胶片 · 光影CLAPPERBOARD · 55 个分类
光影流年-精彩电影分享网 Clapperboard
场次 15625554 分析 2026.12.04 —

Android编程实例分析 手把手带你拆解一个完整App项目 从界面布局到数据存储 每一步都讲得明明白白 新手照着做就能跑起来

分类
分析
编号
15625554
录入
12.04
更新
12.04
场次 · 19:30 已开场

这篇文章是一次完整的 Android 编程实例分析——我们手把手拆解一个「待办清单」App 的完整开发流程:从 Android Studio 建项目、写界面布局,到用 Room 数据库实现本地数据存储,每一步都给出能直接运行的代码。新手照抄跑通一遍,通常 1 到 2 小时就能看到第一个自己写的 App 在模拟器里跑起来。

动手之前:环境怎么搭、项目怎么建?

写 Android App 前,先把工具备齐:

  • Android Studio:官网 developer.android.com/studio 下载最新版,安装时勾选「Standard」即可,安装包约 1GB,SDK 组件会再下载 3~4GB。
  • 模拟器镜像:打开 SDK Manager,建议选 API 34(Android 14)对应的系统镜像,x86_64 架构的模拟器速度快。
  • 编程语言选 Kotlin:Google 官方已把 Kotlin 作为首选语言,语法比 Java 简洁,新手直接学 Kotlin 不用再绕 Java。

新建项目时选 Empty Views Activity 模板(名字带 “Views” 的才是传统 XML 界面那套,别选成 Compose 模板,本文基于 XML 布局,思路更适合新手入门),语言选 Kotlin,最低 SDK 建议 API 24,覆盖约 97% 的安卓设备。点 Finish 等 Gradle 同步完,项目就建好了。

把 build.gradle.kts(Module :app)里的依赖改成下面这样,Room 和协程都要:

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("androidx.recyclerview:recyclerview:1.3.2")
    implementation("androidx.room:room-runtime:2.6.1")
    implementation("androidx.room:room-ktx:2.6.1")
    ksp("androidx.room:room-compiler:2.6.1")
}

同时在最上面应用 KSP 插件(它负责在编译期生成 Room 的代码):

plugins {
    id("com.google.devtools.ksp")
}

注意 KSP 的版本要和项目 Kotlin 版本配套,比如 Kotlin 1.9.0 对应 KSP 1.9.0-1.0.13,版本不匹配会报错,查 Android Studio 提示的对应关系即可。

界面布局怎么搭?新手最容易写乱的地方在哪

Android 的界面写在 XML 布局文件里,放在 res/layout/ 目录下。整个 App 只需要两个布局文件:一个是主界面,一个是列表里每一行长什么样。

activity_main.xml:主界面的骨架

主界面从上到下是:输入框、添加按钮、待办列表。用垂直 LinearLayout 最直观:

<?xml version="="?><!-- 注意第一行应为 <?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/et_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="输入要做的事" />

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加" />
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="12dp" />

</LinearLayout>

这里有个新手必懂的概念:match_parent 表示占满父容器,wrap_content 表示按内容大小自适应,写反了界面就会要么撑满要么缩成一团。输入框用 layout_weight="1" 意思是把剩余宽度全给它,按钮则按内容大小占位——这是让输入框自动伸缩的标配写法。

item_todo.xml:列表里的一行

RecyclerView 本身只是个容器,它里面每一行长什么样,由另一个布局文件决定:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="12dp"
    android:gravity="center_vertical">

    <CheckBox
        android:id="@+id/cb_done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="16sp"
        android:text="示例事项" />

    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除" />

</LinearLayout>

记住这个结构:主界面一个 RecyclerView + 一个”行布局”,列表有 100 条数据也只用一套行布局,系统自动把行复用到屏幕上。这也是为什么 Android 列表性能好的核心原因——复用,而不是真的创建 100 个控件。

RecyclerView 是什么?为什么不能一个个往界面上加控件

RecyclerView 是 Android 提供的列表容器控件,它只负责”显示和回收”列表项,具体内容交给 Adapter(适配器)提供。

新手常见误区是觉得”加一条待办就 add 一个 TextView 到布局里”。这样写界面会随着数据变多越来越卡,内存也爆——因为安卓屏幕一次只显示十几条,你要维护上百个控件完全是浪费。RecyclerView 的做法是:屏幕上需要几条就创建几个”行控件”,往下滑时把划走的行回收、重新绑定新数据,这就是”复用”。列表滚动丝滑和内存占用低,都靠它。

数据存储怎么选?Room 到底是什么

App 的数据存哪儿?常见方案有 SharedPreferences(适合几个键值对)、文件、SQLite 数据库。Room 是 Google 官方提供的 SQLite 封装库,属于 Android 架构组件之一,它把建表、写 SQL 的重复工作自动化,同时把编译期错误提前暴露出来——传统 SQLite 里写错一个表名要到运行时才崩,Room 会在编译时就报错。

一个待办清单用 Room,只需写三个东西:

第一步:定义数据表(Todo 实体类)

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "todo_table")
data class Todo(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val isDone: Boolean = false
)

@Entity 告诉 Room:把这个类映射到数据库的一张表,属性对应列。@PrimaryKey(autoGenerate = true) 表示主键自增,你不用自己编号。isDone 存完成状态,默认 false。

第二步:定义数据操作接口(DAO)

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Update
import androidx.room.Delete
import androidx.room.Query
import kotlinx.coroutines.flow.Flow

@Dao
interface TodoDao {

    @Query("SELECT * FROM todo_table ORDER BY id DESC")
    fun getAll(): Flow<List<Todo>>

    @Insert
    suspend fun insert(todo: Todo)

    @Update
    suspend fun update(todo: Todo)

    @Delete
    suspend fun delete(todo: Todo)
}

DAO(Data Access Object,数据访问对象)就是”数据库操作的菜单”:@Query 里写 SQL,@Insert/@Update/@Delete 让 Room 自动生成实现。返回值用 Flow 是因为数据可能变化,Room 能在数据变化时自动推送新列表给界面。suspend 表示这些操作会挂起,不阻塞主线程——数据库读写必须放后台,这是安卓开发的铁律。

第三步:创建数据库对象

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [Todo::class], version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun todoDao(): TodoDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun get(context: Context): AppDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: Room.databaseBuilder(
                    context,
                    AppDatabase::class.java,
                    "todo.db"
                ).build().also { INSTANCE = it }
            }
    }
}

数据库要全局唯一,用单例模式(@Volatile + synchronized)保证多线程同时取实例时只建一次。version = 1 是数据库版本号,将来改表结构要升级版本并写迁移逻辑。

界面和数据怎么连?用 ViewModel 做中间层

直接让 Activity 操作数据库是反面教材——手机横竖屏切换时 Activity 会销毁重建,连接就断了。ViewModel 是 Android 架构组件中专门用于存放界面数据的类,它的生命周期比 Activity 长,屏幕旋转时数据不会丢。

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.asLiveData
import kotlinx.coroutines.launch

class TodoViewModel(private val dao: TodoDao) : ViewModel() {

    // 数据变化时,界面自动收到新列表
    val todos = dao.getAll().asLiveData()

    fun add(title: String) {
        viewModelScope.launch { dao.insert(Todo(title = title)) }
    }

    fun toggle(todo: Todo) {
        viewModelScope.launch { dao.update(todo.copy(isDone = !todo.isDone)) }
    }

    fun remove(todo: Todo) {
        viewModelScope.launch { dao.delete(todo) }
    }
}

// Activity 里通过工厂把 DAO 传进 ViewModel
class TodoViewModelFactory(private val dao: TodoDao) : ViewModelProvider.Factory {
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return TodoViewModel(dao) as T
    }
}

viewModelScope.launch 是启动协程的写法:数据库操作丢到后台执行,完成后自动回到主线程更新界面,todos 用 asLiveData() 转成 LiveData,界面 observe 它就能”数据变了自动刷新”,不用手动通知。

跑起来看看:最后几行代码

把上面零件装进 MainActivity:

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: TodoViewModel
    private lateinit var adapter: TodoAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val dao = AppDatabase.get(applicationContext).todoDao()
        viewModel = ViewModelProvider(this, TodoViewModelFactory(dao))
            .get(TodoViewModel::class.java)

        adapter = TodoAdapter(
            onToggle = { viewModel.toggle(it) },
            onDelete = { viewModel.remove(it) }
        )

        findViewById<RecyclerView>(R.id.recyclerView).apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = this@MainActivity.adapter
        }

        viewModel.todos.observe(this) { list ->
            adapter.submitList(list)
        }

        findViewById<Button>(R.id.btn_add).setOnClickListener {
            val input = findViewById<EditText>(R.id.et_input)
            val title = input.text.toString().trim()
            if (title.isNotEmpty()) {
                viewModel.add(title)
                input.text.clear()   // 添加后清空输入框
            }
        }
    }
}

最后补上适配器 TodoAdapter:

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class TodoAdapter(
    private val onToggle: (Todo) -> Unit,
    private val onDelete: (Todo) -> Unit
) : RecyclerView.Adapter<TodoAdapter.ViewHolder>() {

    private val items = mutableListOf<Todo>()

    fun submitList(newItems: List<Todo>) {
        items.clear()
        items.addAll(newItems)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_todo, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = items.size

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val checkBox: CheckBox = view.findViewById(R.id.cb_done)
        val textView: TextView = view.findViewById(R.id.tv_title)
        val btnDelete: Button = view.findViewById(R.id.btn_delete)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val todo = items[position]
        holder.textView.text = todo.title
        // 先移除监听再设状态,防止复用时误触发回调
        holder.checkBox.setOnCheckedChangeListener(null)
        holder.checkBox.isChecked = todo.isDone
        holder.checkBox.setOnCheckedChangeListener { _, _ -> onToggle(todo) }
        holder.btnDelete.setOnClickListener { onDelete(todo) }
    }
}

点运行,等模拟器启动(第一次冷启动可能要 1~2 分钟),输入”写周报”点添加、勾选、删除,数据会存进 todo.db,杀掉 App 再打开数据还在——这就是一次完整闭环。

新手最容易踩的 5 个坑

坑 症状 解决办法
在主线程读写数据库 运行报 NetworkOnMainThreadException 或界面卡死 数据库操作全部放进 viewModelScope.launch
忘了加 Room 依赖/插件 编译报找不到 @Entity 检查 room-runtime、room-ktx、ksp 三样都齐
绑定复用行时没清监听 勾一条,其他行跟着变 先 setOnCheckedChangeListener(null) 再设状态
Gradle 版本不匹配 KSP 编译报错 对照 Kotlin 版本换 KSP 版本号
横竖屏切换数据丢失 旋转屏幕列表清空 数据放 ViewModel,别写在 Activity 成员变量里

常见问题

这个项目学完能做什么进阶功能?

基础跑通后,可以自己加:点击列表项进入详情页(用 Intent 传 id)、给 Todo 加 dueDate 字段做到期提醒(闹钟权限)、把 DAO 的 getAll() 改成 WHERE isDone = 0 过滤已完成项。每个功能都是在现有代码上加东西,不需要推倒重来。

Room 和直接写 SQLite 有什么区别?

直接写 SQLite 需要手写建表 SQL、手动管理连接和游标,出错只能运行时排查。Room 自动生成这些样板代码,SQL 在编译期校验,DAO 方法签名和表结构不匹配会直接编译失败,开发效率高且安全。

SharedPreferences 能代替 Room 存待办清单吗?

能存几条,但不适合存列表。因为 SharedPreferences 是键值对格式,存列表要么把整个列表序列化成字符串存一个键,要么每个待办单开一个键,查询、排序、更新都很别扭。数据是结构化列表时,Room 才是正解。

模拟器太卡怎么办?

在模拟器设置里选 x86_64 镜像并开启硬件加速(Windows 上需开启 BIOS 的虚拟化),内存给 2GB 以上。或者直接插真机:开发者选项里打开「USB 调试」,连上后 Run 目标选真机,速度快且更贴近真实体验。

为什么界面数据要放 ViewModel 而不是直接放 Activity?

Activity 在横竖屏切换、配置变更时会被系统销毁重建,成员变量里的数据随之丢失。ViewModel 的生命周期绑定的是整个界面流程,旋转屏幕时它不被销毁,数据自然还在,这也是官方推荐架构里 ViewModel 的核心价值。

Plan · 观影清单观看前核对
先看场次再谈剧情片源确认字幕质量最后入戏留影评
同

同分类场次

same category