0. 前言
上一篇我们介绍了布局性能优化里常用的技巧,比如减少布局层级、按需加载、合并等技巧。这篇是受唯鹿的博客的启发,总结的一些Android布局优化的小技巧,虽然不能达到立竿见影的布局优化效果,毕竟优化是一个持之以恒的过程,但是看完一定会带给你耳目一新的感觉,定会有所收获。本文原创,转载请注明出处:http://blog.csdn.net/seu_calvin/article/details/53389356
1. 用TextView同时显示图片和文字
首先来看一下下面这张效果图:
要实现这个效果,先做其中的一个条目。比如上图中“我的卡劵”部分。很多人是不是想到写一个水平的LinearLayout,并分别填入ImageView、TextView以及最后面的ImageView呢。其实这样写效率是很低的。我们其实可以用TextView同时显示图片和文字。实现如下:
效果图:
结果肯定是和一开始的想法所展现的结果是一样的,但是显然少了两个ImageView和去除嵌套LinearLayout。达到了布局优化的目的。当然drawableTop和drawableBottom这两个属性也可以根据需求使用。为了确保文章的实时更新,实时修改可能出错的地方,请确保这篇是原文,而不是无脑转载来的“原创文”,原文链接为SEU_Calvin的博客。
2. 使用CompoundDrables
上面的效果我们在代码里也可以通过CompoundDrawables实现,利用代码setCompoundDrawables(Drawableleft, Drawable top, Drawable right, Drawable bottom)可以让我们动态去设置图片。下面看一下官方API说明和使用示例:
3. 使用LinearLayout自带的分割线
继续实现一开始的效果图,如下图中两个条目之间是有一个灰色的间隔的:
我以前是用一个带颜色和高度的View来实现的,相信一定有人和我一样。但是相信使用LinearLayout自带的分割线一定会效率更高一些。
核心部分就是android:divider="@drawable/divider",我们在divider.xml中自己画一个带颜色的矩形即可。
showDividers 是分隔线的显示位置,beginning、middle、end分别代表显示在开始、中间、末尾。
还有dividerPadding属性这里没有用到,意思很明确给divider添加padding,感兴趣的同学可以试试。
4. 使用Space控件
最后在上面效果图中的“地址管理”和“检查更新”之间,我们需要留一部分空白,效果图如下:
传统的做法有两种:
(1)添加一个高10dp的透明View。
(2)使用android:layout_marginTop="10dp"。
增加View违背了我们优化布局性能的初衷,使用过多的margin会影响代码的可读性,这时你就可以使用Space,他是一个轻量级的View。它的源码的draw方法中没有绘制任何东西,那么性能肯定是比传统的做法要好啦。使用起来也很简单,在两个TextView之间添加如下代码即可。为了确保文章的实时更新,实时修改可能出错的地方,请确保这篇是原文,而不是无脑转载来的“原创文”,原文链接为SEU_Calvin的博客。
5. 使用TextView的行间距
先看一下要实现的效果图:
用4个TextView,并为它们设置一个垂直的子LinearLayout当然可以实现,但是我们可以通过设置TextView的行间距来进行优化:
可以看到我们仅仅利用android:lineSpacingExtra="8dp"这一行代码就省去了3个TextView。
lineSpacingExtra属性代表的是行间距,默认是0,是一个绝对高度值,同时还有lineSpacingMultiplier属性,它代表行间距倍数,默认为1.0f,是一个相对高度值。如果两者同时设置高度计算规则为mTextPaint.getFontMetricsInt(null) * 行间距倍数 + 行间距。
6. 使用Spannable
先看一下要实现的效果图:
如果实现上图红框中的效果,笨办法就是写三个TextView,“¥”,“价格”,“门市价”分别实现,其实用一个TextView就可以实现:
String text = String.format("¥%s 门市价:¥%s", 18.6, 22);
int z = text.lastIndexOf("门");
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
//颜色
ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#afafaf")), z, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#32BBA9")), 0, z,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
//字号
ssb.setSpan(new AbsoluteSizeSpan(DensityUtil.dip2px(this,10)), 0, text.length(),Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
ssb.setSpan(new AbsoluteSizeSpan(DensityUtil.dip2px(this,16)), 1, z,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
如果不熟悉 String.format()的使用,可以参考 这篇博客。
ForegroundColorSpan用于颜色的设置,AbsoluteSizeSpan用于字号的设置(参数1单位为像素值,需要自己转换一下)。
至此关于布局优化的一些小技巧就介绍到这了,希望对你有用~
也希望看官老爷们多点赞支持~