引言
随着时间的发展,Android版本正在不断更新。随着版本更新带来的系统变化,许多旧版本的应用在新版本上不可避免地出现了兼容性的问题,导致使用体验下降甚至无法使用,这时我们需要做的就是软件版本的升级和适配,这篇教程简单地介绍将一个应用升级到安卓10以及适配新特性的过程。
首先是Google官方的操作流程:
这里用我自己的期中项目Notepad举例:
github地址:https://github.com/ZeroNinx/AS_Dev/tree/master/NotePad
它的目标平台是Android 7(N),没有对黑夜模式的支持,背景色是白色,尽管可以跑,但是在安卓10的手机上运行起来是这样的:
可以看出,原先黑色的字体并不协调,当手机处于黑暗模式的情况下,设置了自定义背景色的菜单却还是白色,如果用户主题为黑色,将会影响观感,因此,我们需要将应用进行适配更新
准备工作
1、一部Android10的手机或模拟器
2、在Android Studio中安装Android10的SDK
3、【可选】将软件的编译版本和目标版本升级到29/30来确保安卓10的兼容性
适配黑暗模式
为了解决黑暗模式的问题,我们首先需要知道安卓10如何分辨是否为黑暗模式,这里Google官方为我们提供了API。
Google官方文档的介绍:
https://developer.android.google.cn/guide/topics/ui/look-and-feel/darktheme
实现
首先在style.mxl主题继承DayNight主题,我们的就有了适配黑夜主题的能力
既然有了夜间模式主题,那接下来就要针对夜间模式做出适配,表现在字体和背景等方面,这些都和value.xml中的值有关,为了适配黑夜模式,我们要将values文件夹复制一份另存为values-night,成功之后AS的values文件夹下会有普通和night两个选项,我们就可以对这两个文件夹里的xml进行编辑进行不同模式的适配看了。
在我们需要适配的xml中,需要分别在values和values-night设定不同的值,而且名字要一样,否则会报错,这里改变了之前看起来不自然的主菜单为例,现在不能将android:xxxColor直接硬编码为"#XXXXX"(颜色代码)了,需要正确改为"@color/xxxxx",因为硬编码是不会被适配的,例如:
lv_index_unit.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@color/colorUnitBackground">
<!--替换背景为动态编码-->
<TextView
android:id="@+id/tv_tag"
android:layout_width="80dp"
android:layout_height="15dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:text="@string/tv_tag"
android:textSize="12sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/tv_text"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/tv_title"
android:layout_width="230dp"
android:layout_height="30dp"
android:layout_marginTop="10dp"
android:gravity="start"
android:orientation="horizontal"
android:text="@string/tv_title"
android:textColor="@colo