【Android Studio开发】生命周期、Activity和组件通信(上)

embedded/2025/3/25 14:44:52/

零、前期配置

1.【Android】模式

2.点击【运行】,弹出模拟器

右侧是模拟机,显示Hello World

3. 打开【activity_main.xml】文件,点击【Design】,然后点击【Component Tree】 

在弹出的Component Tree中右键【main】,选择【Convert view...】

 选中第二个【LinearLayout】 然后点击【Apply】

可见布局发生变化:

 

代码结构也发生变化:


         在 Android 开发里,布局文件、活动文件和配置文件是至关重要的组成部分,编写代码也是按照以上顺序,下面分别为你介绍以下三个文件:

一、布局文件activity_main.xml

布局文件,它定义了界面的外观和结构。布局文件是 XML 格式,存放在 res/layout 目录下。以下是一个简单的线性布局示例,包含一个文本视图和一个按钮:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!" /></LinearLayout>
  • 整体布局:使用 LinearLayout 作为根布局,它就像一个 “盒子”,可以把里面的元素按照一定方向排列(这里默认是水平排列)。
    • android:layout_width="match_parent" 和 android:layout_height="match_parent" 表示这个 “盒子” 的宽度和高度要和它的父容器(也就是手机屏幕)一样大。
    • 设置了android:id="@+id/main",为该布局分配了一个唯一标识符main,以便在Java代码中引用。
  • TextView 文本显示:在这个 “盒子” 里放了一个 TextView,它的作用是显示文本。
    • android:text="Hello World!" 就是要显示的内容
    • android:layout_width="wrap_content" 和 android:layout_height="wrap_content" 表示这个文本框的宽度和高度会根据显示的文本内容自动调整。
    • tools:context=".MainActivity"指定了该布局与MainActivity相关联,便于在设计视图中预览 

二、活动文件MainActivity.java

活动文件,它负责处理业务逻辑和与用户的交互,比如加载布局文件,处理用户的操作等。活动文件通常用 Java 或 Kotlin 编写,存放在 java 或 kotlin 目录下。以下是使用 Java 编写的一个简单活动示例:

package com.example.a04;import android.os.Bundle;import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});}
}

这段Java代码定义了一个名为MainActivity的Android活动类,主要功能如下:

  • 继承与初始化:继承自AppCompatActivity,并重写了onCreate方法,用于初始化活动。
  • 全屏模式支持:调用EdgeToEdge.enable(this)启用边缘到边缘(Edge-to-Edge)显示模式,允许内容延伸到屏幕边缘(如状态栏、导航栏下方)。
  • 设置布局:setContentView() 绑定布局文件,将 XML 布局渲染为可视化界面。通过setContentView(R.layout.activity_main),加载activity_main.xml布局文件作为界面
  • ViewCompat.setOnApplyWindowInsetsListener:给布局根视图(id为main)设置一个监听事件,当系统的状态栏和导航栏的位置发生变化时,就会触发这个事件。在这个事件里,会获取状态栏和导航栏的高度(Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())),然后给布局设置内边距(v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)),这样布局里的内容就不会被状态栏和导航栏挡住了。

三、配置文件AndroidManifest.xml

在 AndroidManifest.xml 文件中声明活动,让系统知道应用中有哪些活动以及它们的入口信息。该文件存放在项目的根目录下。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme._04"tools:targetApi="31"><activityandroid: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>

该AndroidManifest.xml文件定义了Android应用的基本配置和组件信息:

根标签 <manifest>

  • 声明了命名空间xmlns:android和xmlns:tools,用于访问Android框架属性和开发工具属性。

应用级配置<application> 标签:

  • allowBackup="true":允许对这个应用的数据进行备份。
  • label:设置应用的名称,这个名称会显示在手机桌面上。
  • icon 和 roundIcon:指定应用图标资源。
  • theme:设置应用的主题样式为@style/Theme._04。
  • supportsRtl="true":支持从右到左的语言布局。

活动组件声明<activity> 标签:

  • 声明了这个应用里有一个名为MainActivity的活动,并设置为可导出(exported="true")表示这个活动可以被其他应用调用。
  • 通过intent-filter指定该活动为主入口点,包含MAIN动作和LAUNCHER类别。 

<intent-filter> 标签

  • <action android:name="android.intent.action.MAIN" /> 和 <category android:name="android.intent.category.LAUNCHER" />:这两个标签组合起来表示 MainActivity 是这个应用的启动活动,当用户点击手机桌面上的应用图标时,就会启动这个活动,就像打开房子的大门。

四、编写代码步骤---ActivityLifeCycle示例

下面以ActivityLifeCycle示例来进行说明Activity事件回调函数, ActivityLifeCycle示例的运行界面

步骤 1:布局文件

activity_main.xml

  • 在这个示例中,我们将创建一个简单的布局,包含一个TextView和一个Button。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World, ActivityLifeCycleActivity!"android:textSize="24sp" /><Buttonandroid:id="@+id/btn_finish"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="结束程序" /></LinearLayout>

步骤 2:创建活动文件

ActivityLifeCycleActivity.java

  • 创建一个Java类文件,命名为ActivityLifeCycleActivity.java
  • 该文件将继承自Activity类,并重写其生命周期回调方法。
package com.example.a04;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;public class ActivityLifeCycleActivity extends Activity {private static String TAG = "LIFECYCLE";// 完全生命周期开始时被调用,初始化Activity@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(TAG, "(1) onCreate()");// 定义按钮和按钮监听函数Button button = (Button) findViewById(R.id.btn_finish);button.setOnClickListener(new View.OnClickListener() {public void onClick(View view) {finish();}});}// 可视生命周期开始时被调用,对用户界面进行必要的更改@Overridepublic void onStart() {super.onStart();Log.i(TAG, "(2) onStart()");}// 在onStart()后被调用,用于恢复onSaveInstanceState()保存的用户界面信息@Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);Log.i(TAG, "(3) onRestoreInstanceState()");}// 在活动生命周期开始时被调用,恢复被onPause()停止的用于界面更新的资源@Overridepublic void onResume() {super.onResume();Log.i(TAG, "(4) onResume()");}// 在活动生命周期结束时被调用,用来保存界面信息@Overridepublic void onSaveInstanceState(Bundle savedInstanceState) {super.onSaveInstanceState(savedInstanceState);Log.i(TAG, "(5) onSaveInstanceState()");}// 在重新进入可视生命周期前被调用,载入界面所需要的更改信息@Overridepublic void onRestart() {super.onRestart();Log.i(TAG, "(6) onRestart()");}// 在活动生命周期结束时被调用,用来保存持久的数据。@Overridepublic void onPause() {super.onPause();Log.i(TAG, "(7) onPause()");}// 在可视生命周期结束时被调用,释放或调整 应用对用户不可见时不需要的资源。@Overridepublic void onStop() {super.onStop();Log.i(TAG, "(8) onStop()");}// 在完全生命周期结束时被调用,释放资源,包括线程、数据连接等@Overridepublic void onDestroy() {super.onDestroy();Log.i(TAG, "(9) onDestroy()");}
}

步骤 3:配置文件

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme._04"tools:targetApi="31"><activityandroid:name=".ActivityLifeCycleActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

项目结构:

        按照这样的顺序编写代码,能让你先设计好界面,再实现业务逻辑,最后完成应用的整体配置,使开发过程更加有条理。

步骤 4:LogCat

        上面的程序主要通过在生命周期函数中添加“日志点”的方法进行调试, 程序的运行结果将会显示在LogCat中,但是LogCat中有很多其他信息。

        所以,为了显示结果易于观察和分析,在LogCat设置过滤器LifeCycleFilter,过滤方法选择by Log Tag,过滤关键字为LIFECYCLE。

【运行】程序,此时LogCat已经输出124,然后点击【结束程序】

LogCat输出完整结果124789

完全生命周期:


http://www.ppmy.cn/embedded/174778.html

相关文章

QPrintDialog弹出慢的问题

开发环境 操作系统: openkylin2qt版本 : 5.15.10排查过程 首先看下问题的现象, 问题现象 复现问题的demo很简单,只能是从跟踪qt代码方面入手 void MainWindow::on_pushButton_clicked(){QPrinter printer;QPrintDialog dialog(&printer,this);dialog.exec();} 现在需要找一…

Spring(以 Spring Boot 为核心)与 JDK、Maven、MyBatis-Plus、Tomcat 的版本对应关系及关键注意事项

以下是 Spring&#xff08;以 Spring Boot 为核心&#xff09;与 JDK、Maven、MyBatis-Plus、Tomcat 的版本对应关系及关键注意事项&#xff0c;基于最新技术生态整理&#xff1a; 一、Spring Boot 与 JDK 版本对应 Spring Boot 2.x 系列 最低要求&#xff1a;JDK 1.8推荐版本…

报错 - redis - Unit redis.service could not be found.

报错&#xff1a; Unit redis.service could not be found.Could not connect to Redis at 127.0.0.1:6379: Connection refused解决方法&#xff1a; 检查状态、有必要的话 重新安装 Linux 上查看状态 systemctl status redis显示以下内容&#xff0c;代表正常服务 出现下面…

【设计模式】装饰模式

六、装饰模式 装饰(Decorator) 模式也称为装饰器模式/包装模式&#xff0c;是一种结构型模式。这是一个非常有趣和值得学习的设计模式&#xff0c;该模式展现出了运行时的一种扩展能力&#xff0c;以及比继承更强大和灵活的设计视角和设计能力&#xff0c;甚至在有些场合下&am…

NocoBase 本周更新汇总:优化表格区块的列和操作

原文链接&#xff1a;https://www.nocobase.com/cn/blog/weekly-updates-202503020 汇总一周产品更新日志&#xff0c;最新发布可以前往我们的博客查看。 NocoBase 目前更新包括的版本更新包括三个分支&#xff1a;main &#xff0c;next和 develop。 main &#xff1a;截止目…

uniapp中的vue组件与组件使用差异

Vue组件 动态组件 <component> 功能&#xff1a;渲染一个“元组件”为动态组件。依 is 的值&#xff0c;来决定哪个组件被渲染。 平台差异说明&#xff1a; 平台支持情况App√ (Vue2 需传入 String 类型)HarmonyOS NextHBuilderX 4.24H5√微信小程序/支付宝小程序/百度…

基于Python编程语言实现“机器学习”,用于车牌识别项目

基于Python的验证码识别研究与实现 1.摘要 验证码的主要目的是区分人类和计算机&#xff0c;用来防止自动化脚本程序对网站的一些恶意行为&#xff0c;目前绝大部分网站都利用验证码来阻止恶意脚本程序的入侵。 验证码的自动识别对于减少自动登录时长&#xff0c;识别难以识别…

Python 爬取 1688 关键词搜索接口数据返回说明

在当今的电子商务时代&#xff0c;获取商品信息对于商家和消费者都具有重要意义。1688 作为国内知名的 B2B 电商平台&#xff0c;提供了丰富的商品数据。通过利用 Python 爬虫技术&#xff0c;我们可以自动化地获取 1688 平台上按关键字搜索的商品信息&#xff0c;从而为数据分…