第一个Android应用 #

一、创建新项目 #

1.1 启动Android Studio #

打开Android Studio,在欢迎界面点击 New Project。

1.2 选择项目模板 #

Android Studio提供了多种项目模板:

模板 说明
Empty Activity 空白Activity,最简单的模板
Empty Views Activity 传统View系统的空白Activity
Bottom Navigation Activity 底部导航栏应用
Navigation Drawer Activity 侧滑菜单应用
Tabbed Activity 标签页应用

初学者建议选择 Empty Views Activity(传统View系统)或 Empty Activity(Jetpack Compose)。

1.3 配置项目信息 #

字段 说明 示例
Name 应用名称 My First App
Package name 包名 com.example.myfirstapp
Save location 保存位置 /Users/xxx/AndroidStudioProjects/MyFirstApp
Language 开发语言 Kotlin(推荐)
Minimum SDK 最低SDK版本 API 24 (Android 7.0)

点击 Finish 创建项目。

二、项目结构概览 #

创建完成后,项目结构如下:

text
MyFirstApp/
├── app/
│   ├── src/
│   │   ├── main/
│   │   │   ├── java/
│   │   │   │   └── com/example/myfirstapp/
│   │   │   │       └── MainActivity.kt
│   │   │   ├── res/
│   │   │   │   ├── layout/
│   │   │   │   │   └── activity_main.xml
│   │   │   │   ├── values/
│   │   │   │   │   ├── strings.xml
│   │   │   │   │   └── themes.xml
│   │   │   │   └── mipmap-*/
│   │   │   │       └── ic_launcher.png
│   │   │   └── AndroidManifest.xml
│   │   ├── test/
│   │   └── androidTest/
│   └── build.gradle.kts
├── gradle/
├── build.gradle.kts
├── settings.gradle.kts
└── gradle.properties

2.1 MainActivity.kt #

主Activity文件,应用的入口点:

kotlin
package com.example.myfirstapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

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

2.2 activity_main.xml #

布局文件,定义界面结构:

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="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

2.3 AndroidManifest.xml #

应用清单文件,声明应用的基本信息:

xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myfirstapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyFirstApp">
        
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
    </application>

</manifest>

三、修改界面 #

3.1 修改布局文件 #

打开 res/layout/activity_main.xml,修改TextView的内容:

xml
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="欢迎使用Android!"
    android:textSize="24sp"
    android:textColor="#FF5722"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

3.2 添加按钮 #

在布局中添加一个按钮:

xml
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="点击我"
    android:layout_marginTop="16dp"
    app:layout_constraintTop_toBottomOf="@id/textView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent" />

3.3 在代码中引用控件 #

修改 MainActivity.kt

kotlin
package com.example.myfirstapp

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val textView = findViewById<TextView>(R.id.textView)
        val button = findViewById<Button>(R.id.button)
        
        button.setOnClickListener {
            textView.text = "按钮被点击了!"
            Toast.makeText(this, "Hello, Android!", Toast.LENGTH_SHORT).show()
        }
    }
}

四、运行应用 #

4.1 使用模拟器运行 #

  1. 点击工具栏的设备下拉框,选择已创建的模拟器
  2. 点击绿色的运行按钮(三角形)或按 Shift+F10
  3. 等待应用编译安装并启动

4.2 使用真机运行 #

  1. 手机开启开发者选项:
    • 设置 -> 关于手机 -> 连续点击"版本号"7次
  2. 开启USB调试:
    • 设置 -> 开发者选项 -> USB调试
  3. 用USB连接电脑
  4. 在Android Studio中选择连接的设备
  5. 点击运行按钮

4.3 无线调试(Android 11+) #

  1. 手机和电脑连接同一WiFi
  2. 设置 -> 开发者选项 -> 无线调试
  3. 点击"使用配对码配对设备"
  4. 在Android Studio中配对并连接

五、调试应用 #

5.1 使用Logcat #

Logcat是Android的日志系统,用于查看应用输出。

添加日志 #

kotlin
import android.util.Log

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        Log.d(TAG, "onCreate: Activity创建")
        Log.i(TAG, "onCreate: 信息日志")
        Log.w(TAG, "onCreate: 警告日志")
        Log.e(TAG, "onCreate: 错误日志")
    }
}

日志级别 #

级别 方法 说明
VERBOSE Log.v() 冗余信息
DEBUG Log.d() 调试信息
INFO Log.i() 一般信息
WARN Log.w() 警告信息
ERROR Log.e() 错误信息
ASSERT Log.wtf() 严重错误

查看Logcat #

  • 底部工具栏点击 Logcat
  • 选择设备和应用进程
  • 使用过滤器筛选日志

5.2 断点调试 #

  1. 在代码行号左侧点击,添加红色断点
  2. 点击调试按钮(虫子图标)或按 Shift+F9
  3. 程序运行到断点会暂停
  4. 使用调试控制:
    • Step Over (F8):执行当前行
    • Step Into (F7):进入方法内部
    • Step Out (Shift+F8):跳出方法
    • Resume (F9):继续运行

5.3 查看变量值 #

  • 鼠标悬停在变量上查看当前值
  • 在 Variables 面板查看所有变量
  • 在 Watches 面板添加监视表达式

六、构建APK #

6.1 生成调试APK #

菜单:Build -> Build Bundle(s) / APK(s) -> Build APK(s)

生成的APK位于:

text
app/build/outputs/apk/debug/app-debug.apk

6.2 生成发布APK #

  1. 菜单:Build -> Generate Signed Bundle / APK
  2. 选择 APK
  3. 创建或选择密钥库
  4. 选择 release 构建变体
  5. 生成的APK位于:
text
app/release/app-release.apk

七、项目配置 #

7.1 build.gradle.kts (Module级) #

kotlin
plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.example.myfirstapp"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.myfirstapp"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.11.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
}

7.2 添加依赖 #

dependencies 块中添加:

kotlin
dependencies {
    // 添加网络库
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    
    // 添加图片加载库
    implementation("com.github.bumptech.glide:glide:4.16.0")
}

添加后点击 Sync Now 同步项目。

八、总结 #

本章我们完成了:

  1. 创建第一个Android项目
  2. 了解项目基本结构
  3. 修改界面布局
  4. 添加按钮点击事件
  5. 运行和调试应用
  6. 生成APK文件

现在你已经成功创建了第一个Android应用!接下来我们将深入学习Android项目的详细结构。

最后更新:2026-03-26