2014年1月6日 星期一

Android 開發 (十) ViewStub

為何要使用viewstub

在寫android app時畫layout時必須要十分小心,否則將會導致顯示畫面不順(頓)或者out of memory。
在畫layout時即使設定View.visible(Gone),該View依然會消耗資源,解決的方法就是使用viewstub,ViewStub 是個非常輕量的view, 只有在Viewstub被inflat或visible之後才會佔空間
這也代表著,我們可以決定他何時要被inflat,我們可以在任何我們需要使用時才inflat他,例如button click之後 inflat 我們需要的UI

舉例來說

viewstub 可以用來實現 facebook的  ....更多
當按下時,就可以讀取新的view 進來
使用viewstub可以增加Page在初始化時的效率,避免畫了其他暫時不會被使用到的view,進而增加效率。

如何使用viewStub

<ViewStub
        android:id="@+id/stub"
        android:layout="@layout/mylayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
其中 layout 為 當我們inflat時產生的layout   例如

mylayout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
  
    <TextView
        android:id="@+id/Mytext"
        android:text="Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

接著在任意想要inflat 的時候使用

View view = viewStub.inflate();
TextView txtTextView = (TextView)view.findViewById(R.id.Mytext);
txtTextView.setText("What is this");


附上簡單的 sample code

沒有留言:

張貼留言