您的位置:首页 > 其它

[Andorid应用开发]-(4)布局优化原则及方法

2013-04-26 12:43 218 查看
前面说到性能优化,主要是针对Java代码进行优化的,这篇文章分享布局优化。布局的优化主要依据下面的原则:

  一、避免不必要的嵌套,不要把一个布局放置在其他布局里面,除非是必要的;

  二、避免使用太多试图,在一个布局中每增加一个新的视图,都会在inflate操作耗时和消耗资源。任何时候都不要在一个布局中包含超过80个视图,否则,消耗在inflate操作上的时间会很大。

  三、避免深度嵌套,布局可以任意嵌套,这很容易创建复杂和深度嵌套的布局层次。如果没有硬件限制,将嵌套限制在10层以下是最好的实践。

    从上面三点优化原则中可总结为:布局的优化主要是深度和广度,深度的表现主要在于布局的嵌套使用,广度的表现主要是包含过多的视图。

    我不知道三条原则中超过80个视图和10层的数据时如何得到的。但在我开发的过程中单个Activity显示的自定义视图个数没有超过20个的,层数没有超过4层的。我个人认为如果不是太大、太特殊的项目超过20个视图,4层就必须要优化设计了。比如说现在要设计一个拨号界面,其中包括0-9、*、#等字符,是按LineaLayout来嵌套Button实现?还是用一个GridView来减少Button的个数从而减少冗余的代码?我建议使用GridView来实现~

    其中提到的还有深度优化的问题。这里有必要使用Android SDK提供的hierarchyviewer 工具来分析深度优化的问题。下面我们通过一个HelloWorld来分析布局结构问题

    首先新建一个工程,不做任何改动,使用hierarchyviewer查看布局结构(hierarchyviewer的使用很简单,运行模拟器或者真机连接上ADB打开hierarchyviewer找到工程的包名打开即可)

 

 


    一个未作任何改动的HelloWorld程序就有那么多层次结构?是的,我们要做的布局就是红色标记的部分,从图中可以看出自定义的所有布局都继承FrameLayout。所谓的深度优化就是从这里开始的。布局的优化主要是从标签开始进行,下面将重点介绍以下三个标签:<merge>、<ViewStub>、<include>

1、  Merge:merge标签主要用于减少View树的层次来达到优化的目的。请看一个简单的布局代码。

[html]

<SPAN style="FONT-SIZE: 16px"><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    android:orientation="vertical"> 

    <TextView 

        android:layout_width="fill_parent" 

        android:layout_height="wrap_content" 

        android:text="@string/hello"/> 

</FrameLayout></SPAN> 

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical">

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/hello"/>

</FrameLayout>

结构图

 


    通过hierarchyviewer显示的树结构,可以看到自定义的布局FrameLayout视图从Framelayout布局继承而来,然而自定义的FrameLayout其实在此没有起到任何作用,那么好,既然merge是用于减少View树的层次来优化的,换成merge标签会是什么效果呢?

代码是这样的:

[html]

<merge xmlns:android="http://schemas.android.com/apk/res/android" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    android:orientation="vertical"> 

    <TextView 

        android:layout_width="fill_parent" 

        android:layout_height="wrap_content" 

        android:text="@string/hello"/> 

</merge> 

<merge xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical">

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/hello"/>

</merge>

结构图:

 



通过修改布局的方式有效对布局进行“深度优化”这是一种非常好的方法。

2、  ViewStub:这个标签的最大作用在于,被他包含的所有Views在默认状态下不会占用任何内存空间,而且在默认状态下它是不可见的。

3、  Include:可以通过这个标签直接加载外部的xml到当前结构中,是复用UI资源的常用标签。

 

 作者:tangcheng_ok

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: