Android开发首页投稿(暂停使用,暂停投稿)程序员

Android群英传读书笔记(第十章)

2016-03-23  本文已影响1291人  青藤绿

上一章

本章主要介绍的是android的性能优化。

1.布局优化

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="0dp"
      android:layout_height="0dp"
      android:textSize="20sp"
      android:text="this is a common ui">
</TextView>

然后在布局中进行引用:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <include
        layout="@layout/test"
        android:layout_width="100dp"
        android:layout_height="50dp" />
</RelativeLayout>

如果你需要在<include>标签中覆盖类似原布局中android:layout_xxxxx属性,就必须在<include>标签中同时指定android:layout_widthandroid:layout_height属性。

* 使用`<ViewStub>`实现View的延迟加载
`<ViewStub>`是个非常轻量级的组件,不仅不可视而且大小为0。这个布局在初始化时不需要显示,只有在某些情况下才显示出来。下面是实例代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="not often use" />
</RelativeLayout>

使用<ViewStub>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ViewStub
        android:id="@+id/view_stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout="@layout/test" />
</RelativeLayout>
      ViewStub viewStub= (ViewStub) findViewById(R.id.view_stub);
      //下面两个方法都是用来实现延迟加载的,区别是inflate()方法会返回引用的布局。
      viewStub.setVisibility(View.VISIBLE);
      View view=viewStub.inflate();
      TextView tv= (TextView) view.findViewById(R.id.tv);

<ViewStub>标签与设置View.GONE这种方式的区别在于<ViewStub>标签只在显示时渲染整个布局,而设置View.GONE这种方式在初始化时就已经加载了,所以相比之下<ViewStub>更有效率。

2.内存优化

本章节后面还介绍了Lint、MemoryMonitor、TraceView、MAT等工具来分析内存的使用情况,这里就不做记录了!

上一篇 下一篇

猜你喜欢

热点阅读