1.使用一张图,实现不同颜色
比如UI要我们实现这种效果,一般都是给我们2张图,如果我们要在xhdpi,xxhdpi,xxxhdpi中都放的话,总共需要放6张图,但是如果使用tint
,就只需要放3张图即可
在ImageView标签里面,加上
tint
指定颜色
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/card"
android:tint="@color/red"/>
2.使用tint实现selector效果
比如,图片默认是灰色,点击变成红色,松手又恢复成灰色,这里我们只用一张图片实现
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:src="@drawable/tint_src_selector"
android:tint="@color/tint_color_selector"/>
在src
目录下新建一个color
目录,存放我们的tint_color_selector.xml
文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/red" android:state_pressed="true" />
<item android:color="@color/gray" />
</selector>
在drawable
目录下,新建我们的tint_src_selector.xml
文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/card" android:state_pressed="true" />
<item android:drawable="@drawable/card" />
</selector>
3.无需国际化时,只保留中文资源
一般我们在项目中,都会这样写
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/app_name" />
在打包时,系统会生成很多国家的语言,如果我们不做国际化的app,就只需要中文即可,所以,我们可以在app
目录下的build.gradle
文件中,加上resConfigs('zh-rCN')
defaultConfig {
...
//只保留指定的和默认的资源
resConfigs('zh-rCN')
}
4.合理配置so库
在引入so库的时候,一般都有arm64-v8a,armeabi,armeabi-v7a,mips,mips-64,x86,x86_64
这种目录,在打包的时候,如果不进行筛选配置,会将这所有的so库都打包到我们的apk里面,这无疑增加了很多不必要的库。那么如何配置so库的筛选呢?
首先我们熟悉一下,各种文件夹代表的含义
确定需求后,在app
下的build.gradle
中添加过滤代码
defaultConfig {
...
ndk {
//根据需要 自行选择添加的对应cpu类型的.so库。
abiFilters 'armeabi-v7a', 'x86'
}
}
各版本分析如下:
- mips / mips64: 极少用于手机可以忽略
- x86 / x86_64: 平板,虚拟机,基本可以忽略
- armeabi: ARM v5 这是相当老旧的一个版本,缺少对浮点数计算的硬件支持,在需要大量计算时有性能瓶颈
- armeabi-v7a: ARM v7 目前主流版本
- arm64-v8a: 64位支持
6.代码混淆
buildTypes {
release {
//开启代码混淆
minifyEnabled true
}
}
7.资源压缩
把没有用到的资源,进行压缩处理,不会进行物理上的删除操作
buildTypes {
release {
//开启资源压缩
shrinkResources true
}
}
如果有部分资源你不想压缩,也可以自己指定,创建res/raw/keep.xml
文件
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
tools:keep="@layout/l_used_a,@drawable/l_used_b*"
tools:discard="@layout/unused2" />
- tools:keep :指定每个要保留的资源
- tools:discard :指定每个要舍弃的资源
- *:使用星号字符作为通配符
8.使用webp代替png
webp
格式是谷歌推出的一种有损压缩格式,这种图片格式相比png
或jpg
格式的图片损失的质量几乎可以忽略不计,但是压缩后的图片体积却比png
或jpg
要小很多。
比如下图,从1.1M压缩到了60.4K
如何把png
转换成webp
找到你要压缩的png,右键,
选择最下面的 然后点击
OK
即可。
网友评论