深入分析 Android Activity (八)

文章目录

    • 深入分析 Android Activity (八)
    • 1. Activity 的资源管理
      • 1.1 使用资源 ID
      • 1.2 动态加载资源
      • 1.3 资源的本地化
      • 1.4 使用 TypedArray 访问资源
    • 2. Activity 的配置变更处理
      • 2.1 在 Manifest 文件中声明配置变更
      • 2.2 重写 `onConfigurationChanged` 方法
      • 2.3 保存和恢复实例状态
    • 3. Activity 的视图层次结构
      • 3.1 使用 View Hierarchy Inspector
      • 3.2 优化布局层次结构
      • 3.3 了解 View 的绘制流程
    • 4. Activity 的性能优化
      • 4.1 避免主线程阻塞
      • 4.2 使用 ViewStub 延迟加载
      • 4.3 优化布局渲染
    • 总结

深入分析 Android Activity (八)

1. Activity 的资源管理

在 Android 应用开发中,合理的资源管理可以提高应用的效率和用户体验。资源管理涉及到布局文件、字符串、图片、颜色等各种资源的使用和管理。

1.1 使用资源 ID

在代码中引用资源时,可以通过资源 ID 来访问这些资源。

// Accessing a string resource
String myString = getString(R.string.my_string);

// Accessing a color resource
int myColor = ContextCompat.getColor(this, R.color.my_color);

// Accessing a drawable resource
Drawable myDrawable = ContextCompat.getDrawable(this, R.drawable.my_drawable);

1.2 动态加载资源

动态加载资源在不同的场景中非常有用,比如根据用户选择加载不同的布局或图片。

// Dynamically loading a layout
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_layout, null);

// Dynamically loading a drawable
Drawable drawable = getResources().getDrawable(R.drawable.my_drawable, getTheme());

1.3 资源的本地化

Android 提供了资源的本地化支持,可以根据用户的语言和地区自动加载相应的资源。

<!-- res/values/strings.xml -->
<string name="hello">Hello</string>

<!-- res/values-es/strings.xml -->
<string name="hello">Hola</string>
// Getting localized string resource
String hello = getString(R.string.hello);

1.4 使用 TypedArray 访问资源

TypedArray 是一种方便的方式,可以批量访问一组资源。

<!-- res/values/attrs.xml -->
<declare-styleable name="MyCustomView">
    <attr name="customColor" format="color" />
    <attr name="customSize" format="dimension" />
</declare-styleable>
// Accessing resources via TypedArray
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
int customColor = a.getColor(R.styleable.MyCustomView_customColor, Color.BLACK);
int customSize = a.getDimensionPixelSize(R.styleable.MyCustomView_customSize, 0);
a.recycle();

2. Activity 的配置变更处理

配置变更(如屏幕旋转、语言更改等)会导致 Activity 被销毁并重新创建。开发者可以通过重写 onConfigurationChanged 方法来处理特定配置变更,避免 Activity 重新创建。

2.1 在 Manifest 文件中声明配置变更

<activity android:name=".MyActivity"
    android:configChanges="orientation|screenSize|keyboardHidden">
</activity>

2.2 重写 onConfigurationChanged 方法

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Handle configuration changes
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // Handle landscape orientation
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        // Handle portrait orientation
    }
}

2.3 保存和恢复实例状态

Activity 被销毁并重新创建时,可以使用 onSaveInstanceStateonRestoreInstanceState 保存和恢复实例状态。

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("key", "value");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        String value = savedInstanceState.getString("key");
        // Use the restored data
    }
}

3. Activity 的视图层次结构

Activity 的视图层次结构由多个 ViewGroupView 组成。理解视图层次结构有助于优化布局和性能。

3.1 使用 View Hierarchy Inspector

Android Studio 提供了 View Hierarchy Inspector 工具,可以用来分析和调试视图层次结构。

// Use View Hierarchy Inspector to analyze the view hierarchy

3.2 优化布局层次结构

过多的嵌套布局会影响性能。使用 ConstraintLayout 可以减少嵌套层次,提高性能。

<!-- Using ConstraintLayout to reduce nesting -->
<ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</ConstraintLayout>

3.3 了解 View 的绘制流程

View 的绘制流程包括测量(measure)、布局(layout)和绘制(draw)。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // Measure child views
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    // Position child views
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // Draw view content
}

4. Activity 的性能优化

优化 Activity 的性能可以提高应用的响应速度和用户体验。

4.1 避免主线程阻塞

长时间的操作应在后台线程中完成,避免阻塞主线程。

// Performing a long-running operation on a background thread
new Thread(new Runnable() {
    @Override
    public void run() {
        // Long-running operation
        final String result = performOperation();
        
        // Post result back to the main thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // Update UI with the result
                textView.setText(result);
            }
        });
    }
}).start();

4.2 使用 ViewStub 延迟加载

ViewStub 是一个轻量级的视图,可以用来延迟加载布局。

<!-- Using ViewStub to delay load a layout -->
<ViewStub
    android:id="@+id/viewStub"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout="@layout/my_layout" />
// Inflating the ViewStub
ViewStub viewStub = findViewById(R.id.viewStub);
View inflated = viewStub.inflate();

4.3 优化布局渲染

减少布局层次和优化布局可以提高渲染性能。使用 ConstraintLayout 替代嵌套的 LinearLayoutRelativeLayout

<!-- Optimizing layout with ConstraintLayout -->
<ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</ConstraintLayout>

总结

通过对 Android Activity 的深入理解和灵活应用,可以实现丰富的用户体验和高效的应用程序。理解其生命周期、权限管理、数据传递、动画效果、导航和返回栈管理、资源管理、配置变更处理、视图层次结构、性能优化等方面的知识,有助于开发出性能优异且用户友好的应用程序。不断学习和实践这些知识,可以提升应用程序的质量和用户满意度。

欢迎点赞|关注|收藏|评论,您的肯定是我创作的动力

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/652242.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

MySQL--InnoDB体系结构

目录 一、物理存储结构 二、表空间 1.数据表空间介绍 2.数据表空间迁移 3.共享表空间 4.临时表空间 5.undo表空间 三、InnoDB内存结构 1.innodb_buffer_pool 2.innodb_log_buffer 四、InnoDB 8.0结构图例 五、InnoDB重要参数 1.redo log刷新磁盘策略 2.刷盘方式&…

联想应用商店开发者常见问题FAQ

Phone/Pad应用常见问题 应用上传FAQ Q. 上传apk包时&#xff0c;提示“该包名已存在”如何处理&#xff1f; A&#xff1a;若应用包名出现冲突&#xff0c;请先核实该账号是否已存在该包名产品&#xff0c;若不在该账号下&#xff0c;请进行应用认领。 Q. 应用是否可以授权…

计算机网络——TCP / IP 网络模型

OSI 七层模型 七层模型是国际标准化的一个网络分层模型&#xff0c;大体结构可以分成七层。每层提供不同的功能。 图片来源 JavaGuide 但是这样七层结构比较复杂&#xff0c;不太实用&#xff0c;所以有了 TCP / IP 模型。 TCP / IP 网络模型 TCP / IP 网络模型可以看作是 O…

Overall Accuracy(OA)、Average Accuracy(AAcc)计算公式

四个重要的指标&#xff1a; True Positive&#xff08;TP&#xff09;、False Positive&#xff08;FP&#xff09;、True Negative&#xff08;TN&#xff09;和False Negative&#xff08;FN&#xff09;。 TP表示分类器预测结果为正样本&#xff0c;实际也为正样本&#xf…

第16篇:JTAG UART IP应用<三>

Q&#xff1a;如何通过HAL API函数库访问JTAG UART&#xff1f; A&#xff1a;Quartus硬件工程以及Platform Designer系统也和第一个Nios II工程--Hello_World的Quartus硬件工程一样。 Nios II软件工程对应的C程序调用HAL API函数&#xff0c;如open用于打开和创建文件&#…

感觉是通俗易懂的大模型入门(一)

最近人工智能非常火爆,大家可能经常听到AI、深度学习、大语言模型等名词。但真正能够将它们拆开来细致讲解的内容并不多。我大学就是学这个的,毕业后一直从事这个领域的工作。所以我打算今年陆续做一些这方面的科普,也借此机会复习巩固一下自己的知识体系。 今天就算是第一期,…

POLYGON - Elven Realm - Low Poly 3D Art by Synty(低多边形精灵王国)

Synty Studios™展示:POLYGON-精灵王国 精灵王国隐藏在群山之间,远离非魔法生物的控制。 精灵人以符文之花为动力,将其作为病房、电源、武器附魔和连接他们陆地之间的门户。 主要功能 -700多项独特资产 -模块化建筑系统,包括悬崖和瀑布。 -包括详细的演示场景 资产 角色(x…

基于Cortex的MCU设计

基于Cortex的MCU设计 今日更新的存货文档&#xff0c;发现日更文章还是很花时间的。保证一周更新三篇文章就行啦&#xff0c;本篇文章的内容起始主要取自于《Cortex-M3 权威指南》和知网下载的论文。写的不详细&#xff0c;想进一步了解的就去看这篇文档或网上找别的资料&#…

mysql实战——mysql5.7保姆级安装教程

1、上传 上传5.7压缩包到/usr/local目录下 2、解压 cd /usr/local tar -zxvf mysql--5.7.38-linux-glibc2.12-x86_64.tar.gz mv mysql-5.7.38-linux-glibc2.12-x86_64/ mysql 3、创建mysql用户组和用户 groupadd mysql useradd -g mysql mysql 4、创建数据目录data&#xf…

如何设置远程桌面连接?

远程桌面连接是一种方便快捷的远程访问工具&#xff0c;可以帮助用户在不同地区间快速组建局域网&#xff0c;解决复杂网络环境下的远程连接问题。本文将针对使用远程桌面连接的操作步骤进行详细介绍&#xff0c;以帮助大家快速上手。 步骤一&#xff1a;下载并安装远程桌面连接…

柳宗元,政治坎坷与文学辉煌的交织

&#x1f4a1; 如果想阅读最新的文章&#xff0c;或者有技术问题需要交流和沟通&#xff0c;可搜索并关注微信公众号“希望睿智”。 柳宗元&#xff0c;字子厚&#xff0c;生于唐代宗大历年间&#xff08;公元773年&#xff09;&#xff0c;卒于唐宪宗元和年间&#xff08;公元…

Python批量docx或doc文档转换pdf

说明&#xff1a; 1、因为项目需要&#xff0c;需要手动将十几个word文档转换成pdf文档 2、python请安装3.9.0以上&#xff0c;否则一些依赖库无法正常用 #! /usr/bin/python3 # -*- coding: utf-8 -*-import os import comtypes.client# 批量将docx文件转换pdf文件 def docx_t…

OpenBMC相关的网站

openbmc官方网站 https://github.com/openbmchttps://github.com/openbmc Dashboard [Jenkins]https://jenkins.openbmc.org/ https://gerrit.openbmc.org/Gerrit Code Reviewhttps://gerrit.openbmc.org/ Searchhttps://grok.openbmc.org/ openbmc参考网站 https://www.c…

脱产二战Top3:终将梦校纳入囊中!

这个系列会邀请上岸学长学姐进行经验分享~ 今天分享经验的同学是小马哥819全程班的学员&#xff0c;二战高分上岸上海交通大学&#xff01; 经验分享 在去年考研上交失利后&#xff0c;我选择了在家脱产二战一年&#xff0c;所幸还算取得了比较理想的结果。 我本科中部地区…

攒粒是什么?怎么用攒粒赚钱?

攒粒简介 攒粒的前身是91问问&#xff0c;隶属于上海道道永泉市场调查有限公司&#xff0c;是一家专业的全球在线调研服务公司&#xff0c;也是是国内排名前列的社区调查之一&#xff0c;10年在线调研&#xff0c;600万会员亲身体验&#xff0c;提供网络调查、市场调查、问卷调…

KAN(Kolmogorov-Arnold Network)的理解 1

系列文章目录 第一部分 KAN的理解——数学背景 文章目录 系列文章目录前言KAN背后的数学原理&#xff1a;Kolmogorov-Arnold representation theorem 前言 这里记录我对于KAN的探索过程&#xff0c;每次会尝试理解解释一部分问题。欢迎大家和我一起讨论。 KAN tutorial KAN背…

如何从 Android 恢复已删除的相机照片?(7 种行之有效的方法)

如今&#xff0c;随着智能手机的不断创新和突破&#xff0c;我们可以毫不费力地用安卓手机相机拍摄高清照片。然而&#xff0c;随着安卓手机中相机照片的积累&#xff0c;有时我们可能会因为各种原因丢失这些相机照片。那么如何从安卓设备恢复已删除的相机照片就成了困扰许多人…

Megatron-LM源码系列(八): Context Parallel并行

1. Context Parallel并行原理介绍 megatron中的context并行(简称CP)与sequence并行(简称SP)不同点在于&#xff0c;SP只针对Layernorm和Dropout输出的activation在sequence维度上进行切分&#xff0c;CP则是对所有的input输入和所有的输出activation在sequence维度上进行切分&…

06.部署jpress

安装mariadb数据 yum -y install mariadb-server #启动并设置开启自启动 systemctl start mariadb.service systemctl enable mariadb.service数据库准备 [rootweb01 ~]# mysql Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id…

HCIP-Datacom-ARST自选题库_10_其他多选【48道题】

1.为什么说可以通过提高链路带宽容量来提高网络的QoS? 链路带宽的增加减小了拥塞发生的几率从而减少了云包的数量 链路带宽的增加可以增加控制协议的可用带宽 链路带宽的增加意味着更小的延迟和抖动 链路带宽的增加可以支持更高的流量 2.当拥塞发生时&#xff0c;通常会影…