Android布局效能最佳化—從源碼角度看ViewStub消極式載入技術

來源:互聯網
上載者:User

標籤:效能最佳化   標籤   布局   viewstub   源碼   

在項目中,難免會遇到這種需求,在程式運行時需要動態根據條件來決定顯示哪個View或某個布局,最通常的想法就是把需要動態顯示的View都先寫在布局中,然後把它們的可見度設為View.GONE,最後在代碼中通過控制View.VISIABLE動態更改它的可見度。這樣的做法的優點是邏輯簡單而且控制起來比較靈活。但是它的缺點就是,耗費資源,雖然把View的初始可見View.GONE但是在Inflate布局的時候View仍然會被Inflate,也就是說仍然會建立對象,會被執行個體化,會被設定屬性。也就是說,會耗費記憶體等資源。

推薦的做法是使用android.view.ViewStub,ViewStub是一個輕量級的View,使用非常簡單:

mViewStub = (ViewStub) this.findViewById(R.id.viewstub);

mViewStub.inflate();

它一個不可見的,不佔布局位置,佔用資源非常小的控制項,相當於一個“佔位控制項”。使用時可以為ViewStub指定一個布局,在Inflate布局的時候,只有ViewStub會被初始化,然後當ViewStub被設定為可見的時或調用了ViewStub.inflate()的時候,ViewStub所指向的布局就會被inflate執行個體化,且此布局檔案直接將當前ViewStub替換掉,然後ViewStub的布局屬性(layout_margin***、layout_width等)都會傳給它所指向的布局。這樣,就可以使用ViewStub在運行時動態顯示布局,節約記憶體資源。

下面我們從ViewStub源碼來看下inflate()方法的實現原理:

<span style="color:#333333;"> public View inflate() {        final ViewParent viewParent = getParent();        if (viewParent != null && viewParent instanceof ViewGroup) {            if (mLayoutResource != 0) {                final ViewGroup parent = (ViewGroup) viewParent;                final LayoutInflater factory;                if (mInflater != null) {                    factory = mInflater;                } else {                    factory = LayoutInflater.from(mContext);                }                final View view = factory.inflate(mLayoutResource, parent,                        false);                if (mInflatedId != NO_ID) {                    view.setId(mInflatedId);                }                final int index = parent.indexOfChild(this);                </span><span style="color:#cc0000;">parent.removeViewInLayout(this);</span><span style="color:#333333;">                final ViewGroup.LayoutParams layoutParams = getLayoutParams();                if (layoutParams != null) {                    parent.addView(view, index, layoutParams);                } else {                    parent.addView(view, index);                }                mInflatedViewRef = new WeakReference<View>(view);                if (mInflateListener != null) {                    mInflateListener.onInflate(this, view);                }                return view;            } else {                throw new IllegalArgumentException("ViewStub must have a valid layoutResource");            }        } else {            throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");        }    }</span>
我們先從方法的入口開始看:

1、在第2行,首先是得到ViewStub它的父視圖對象。

2、然後在第4行一開始肯定是能進入判斷的,mLayoutResource就是需要inflate的布局資源,然後在第13行填充這個布局資源。

3、然後在第21行,重要的來了,parent.removeViewInLayout(this);這段代碼是什麼意思呢?看方法名字就知道了,this是代表ViewStub對象,意思就是把當前ViewStub對象從父視圖中移除了。

4、然後第23~28行,就是得到ViewStub的LayoutParams布局參數對象,如果存在就把它賦給被inflate的布局對象,然後把inflate的布局對象添加到父視圖中。
5、最後返回inflate的布局對象。

好了,源碼解析完畢!!!

從上述可知,當我們第二次調用ViewStub.inflate()方法的時候,因為已經移除了ViewStub對象,在第2、4行,得到的viewParent就為null,此時判斷時候就會走else拋出一個IllegalStateException異常:ViewStub must have a non-null ViewGroup viewParent。


需要注意的幾點:

1.ViewStub之所以常稱之為“延遲化載入”,是因為在教多數情況下,程式無需顯示ViewStub所指向的布局檔案,只有在特定的某些較少條件下,此時ViewStub所指向的布局檔案才需要被inflate,且此布局檔案直接將當前ViewStub替換掉,具體是通過viewStub.infalte()或viewStub.setVisibility(View.VISIBLE)來完成。

2.正確把握住ViewStub的應用情境非常重要,因為使用ViewStub可以最佳化布局,一般應用在當前布局或控制項在使用者使用較少情況下,這樣可以提高效能,節約記憶體,加快介面渲染。

3.對ViewStub的inflate操作只能進行一次,因為inflate的時候是將它指向的布局執行個體化並替換掉當前ViewStub本身(由此體現出了ViewStub“佔位”性質),一旦替換後,此時原來的布局檔案中就沒有ViewStub控制項了,因此,如果多次對ViewStub進行infalte,會出現錯誤資訊:ViewStub must have a non-null ViewGroup viewParent。

4.3中所講到的ViewStub指向的布局檔案解析inflate並替換掉當前ViewStub本身,並不是完全意義上的替換(與include標籤不太一樣),替換時,布局檔案的layout params是以ViewStub為準,其他布局屬性是以布局檔案自身為準。

5.ViewStub本身是不可見的,對ViewStub.setVisibility(int visibility)與其他View控制項不一樣,我們可以從源碼角度來看一下ViewStub.setVisibility()方法的作用:


這個方法意思就是ViewStub的setVisibility()設定成View.VISIBLE或INVISIBLE如果是首次使用,都會自動inflate其指向的布局檔案,並替換ViewStub本身,再次使用則是相當於對其指向的布局檔案設定可見度。

好了,原理講了那麼多,來看看代碼怎麼實現吧:

首先看看:


使用了ViewStub的activity_main.xml:

<LinearLayout 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"    android:orientation="vertical"    tools:context="com.example.viewstub.MainActivity" >    <Switch        android:id="@+id/switch1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <ViewStub        android:id="@+id/viewstub"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_marginBottom="10dp"        android:layout_marginLeft="10dp"        android:layout_marginRight="10dp"        android:layout_marginTop="10dp"        android:layout="@layout/hide_layout" /></LinearLayout>
hide_layout.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#00ffff"    android:orientation="vertical" >    <Button        android:id="@+id/hide_layout_btn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:text="Click me" /></LinearLayout>
代碼檔案:

public class MainActivity extends ActionBarActivity {private ViewStub mViewStub;private Switch mSwitch;private boolean flag = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mViewStub = (ViewStub) this.findViewById(R.id.viewstub);//執行個體化ViewStubmSwitch = (Switch) findViewById(R.id.switch1);mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {if (isChecked) {if(!flag){mViewStub.inflate();//ViewStub只能被inflate一次,會返回一個填充資源的View對象//mViewStub.setVisibility(View.VISIBLE);)flag = true;}else{mViewStub.setVisibility(View.VISIBLE);}Button mBtn = (Button) findViewById(R.id.hide_layout_btn);//ViewStub被替換的布局內的控制項mBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getApplicationContext(), "Click me!",Toast.LENGTH_SHORT).show();}});} else {mViewStub.setVisibility(View.GONE);}}});}}

註:使用ViewStub被替換的布局中的控制項,直接findViewById即可。


最後擴充一下在布局最佳化時候常用的其它幾個標籤:

1、布局重用<include />可以通過這個標籤直接載入外部的xml到當前結構中,是複用UI資源的常用標籤

<include />標籤能夠重用布局檔案,簡單的使用如下:

<LinearLayout 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"    android:orientation="vertical"    tools:context="com.example.viewstub.MainActivity" >    <Switch        android:id="@+id/switch1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <include layout="@layout/include_layout" /></LinearLayout>
使用include標籤中布局檔案中的控制項,直接findViewById即可。

2、減少視圖層級<merge />

<merge />標籤在UI的結構最佳化中起著非常重要的作用,它可以刪減多餘的層級,最佳化UI。<merge />多用於替換FrameLayout(因為所有的Activity視圖的根結點都是FrameLayout,如果當前的布局根結點是Framelayout,那麼可以用merge替代,減少多餘的層級)或者當一個布局包含另一個時,<merge />標籤消除視圖階層中多餘的視圖組。例如你的主布局檔案是垂直布局,又include引入了一個垂直布局,這是如果include布局使用的LinearLayout就沒意義了,使用的話反而減慢你的UI渲染。這時可以使用<merge />標籤進行最佳化。

<merge xmlns:android="http://schemas.android.com/apk/res/android">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text=""/>    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text=""/></merge>

轉載請註明出處——http://blog.csdn.net/u010687392









Android布局效能最佳化—從源碼角度看ViewStub消極式載入技術

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.