一、Activity是什么?打个比方就懂了!
如果把一个Android应用比作一家餐厅,那Activity就是餐厅里的每个独立包间:登录页是迎宾厅,主页是用餐区,设置页是后厨操作间。每个“包间”都有自己的装修风格(界面布局)和服务流程(业务逻辑),用户通过“走廊”(Intent)在不同包间穿梭。
作为Android的基本程序单元,Activity需要掌握三个关键特点:
- 用户交互入口:每个屏幕背后都站着一个Activity
- 生命周期自主管理:像人有生老病死,会经历创建、运行、暂停、销毁
- 任务栈管理:类似网页浏览的“后退栈”,保证流畅的返回体验
二、创建Activity的三大核心步骤(附代码)
✅ 步骤1:继承Activity类(基础版or增强版?)
现在Android官方更推荐使用AppCompatActivity而非原生Activity类。为什么?因为它提供了Material Design设计规范的支持,让界面在不同版本系统上都能保持统一美观!
// 基础写法(老古董版)
public class MainActivity extends Activity { ... }
// 推荐写法(时尚弄潮儿版)
public class MainActivity extends AppCompatActivity { ... }
✅ 步骤2:加载界面布局(绑定XML皮肤)
光有骨架不行,还得有皮肤!在onCreate()方法中通过setContentView()绑定XML布局文件:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 加载布局文件
// 这里补充其他初始化代码
}
注意:R.layout.activity_main对应的是res/layout目录下的activity_main.xml文件,这就是Android的资源索引魔法!
✅ 步骤3:清单文件注册(给Activity上户口)
创建完Activity不注册?就像生孩子不上户口——系统根本不认识它!在AndroidManifest.xml中添加:
<application>
<activity android:name=".MainActivity"
android:label="我的主页">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
重点解释:
android:name:Activity的类名(点号开头表示相对路径)intent-filter:定义Activity的特殊能力,上述配置使其成为应用启动入口
三、完整示例:登录页面Activity实战
下面我们打造一个包含邮箱密码输入的登录页,体验真实开发场景:
1. 布局文件 (res/layout/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:padding="20dp"
android:orientation="vertical">
<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入邮箱"
android:inputType="textEmailAddress"/>
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword"
android:layout_marginTop="15dp"/>
<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
android:layout_marginTop="30dp"
android:backgroundTint="#FF6200EE"/>
</LinearLayout>
2. Java代码 (LoginActivity.java)
public class LoginActivity extends AppCompatActivity {
private EditText etEmail, etPassword;
private Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// 初始化视图组件
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
// 设置登录按钮点击事件
btnLogin.setOnClickListener(v -> attemptLogin());
}
private void attemptLogin() {
String email = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
// 简单的输入验证
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "邮箱或密码不能为空", Toast.LENGTH_SHORT).show();
return;
}
// 模拟登录逻辑(实际开发中这里需要网络请求)
if (isValidCredential(email, password)) {
Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
// 通常这里会跳转到主页
} else {
Toast.makeText(this, "邮箱或密码错误", Toast.LENGTH_SHORT).show();
}
}
private boolean isValidCredential(String email, String password) {
// 实际开发中这里需要与服务器验证
return password.length() >= 6 && email.contains("@");
}
}
3. 清单注册别忘了!
<activity android:name=".LoginActivity"
android:label="用户登录"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
四、避坑指南:新手最易翻车的三个点
🚨 坑1:忘记findViewById绑定控件
创建布局后不获取控件实例就直接操作?分分钟空指针异常教你做人!记得在onCreate里完成控件绑定。
🚨 坑2:清单文件注册错误
最常犯的错误:写错Activity类名、忘记加点了、放错位置。记住格式一定是.类名!
🚨 坑3:生命周期方法没重写
onCreate()方法没调用setContentView()?界面一片漆黑别怪我没提醒!
五、Activity生命周期:一张图搞定记忆
虽然本文重点讲创建,但生命周期这个“八卦”必须提前剧透:
- 创建期:onCreate()(一次出生)→ onStart()(准备见客)→ onResume()(正式接客)
- 运行期:用户正在与该Activity交互
- 暂停期:onPause()(有新人抢风头)→ onStop()(彻底失宠)
- 销毁期:onDestroy()(撒由那拉)
记住口诀:创建不回头,暂停可恢复,销毁真再见!
六、总结:现在你也是Activity玩家了!
通过今天的教程,你已经掌握了:
🔹 Activity的三大创建步骤
🔹 登录页面的完整实现
🔹 常见避坑指南
🔹 生命周期核心概念
Activity就像乐高积木的基础模块,掌握了它,你就能搭建出无限可能的Android应用。现在,打开Android Studio,创建一个属于你自己的Activity吧!遇到问题别慌,哪个大神不是从“Hello World”开始的呢?
674

被折叠的 条评论
为什么被折叠?



