Android 抽象布局include merge Viewstub

來源:互聯網
上載者:User

Android 抽象布局include merge Viewstub
1、布局重用

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


1)標籤可以使用單獨的layout屬性,這個也是必須使用的。

2)可以使用其他屬性。標籤若指定了ID屬性,而你的layout也定義了ID,則你的layout的ID會被覆蓋,解決方案。

3)在include標籤中所有的android:layout_*都是有效,前提是必須要寫layout_width和layout_height兩個屬性。

4)布局中可以包含兩個相同的include標籤,引用時可以使用如下方法解決(參考):

 

View bookmarks_container_1= findViewById(R.id.bookmarks_favourite); bookmarks_container_1.findViewById(R.id.bookmarks_list);View bookmarks_container_2 = findViewById(R.id.bookmarks_favourite); bookmarks_container_2.findViewById(R.id.bookmarks_list);
2、減少視圖層級

標籤在UI的結構最佳化中起著非常重要的作用,它可以刪減多餘的層級,最佳化UI。多用於替換FrameLayout或者當一個布局包含另一個時,標籤消除視圖階層中多餘的視圖組。例如你的主布局檔案是垂直布局,引入了一個垂直布局的include,這是如果include布局使用的LinearLayout就沒意義了,使用的話反而減慢你的UI表現。這時可以使用標籤最佳化。




android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add"/>


android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete"/>





現在,當你添加該布局檔案時(使用標籤),系統忽略節點並且直接添加兩個Button。更多介紹可以參考《Android Layout Tricks #3: Optimize by merging》

 

3、需要時使用

標籤最大的優點是當你需要時才會載入,使用他並不會影響UI初始化時的效能。各種不常用的布局想進度條、顯示錯誤訊息等可以使用標籤,以減少記憶體使用量量,加快渲染速度。是一個不可見的,大小為0的View。標籤使用如下:


android:id="@+id/stub_import"
android:inflatedId="@+id/panel_import"
android:layout="@layout/progress_overlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />

當你想載入布局時,可以使用下面其中一種方法:

((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();

當調用inflate()函數的時候,ViewStub被引用的資源替代,並且返回引用的view。 這樣程式可以直接得到引用 的view而不用再次調用函數findViewById()來尋找了。
註:ViewStub目前有個缺陷就是還不支援 標籤。


android:id="@+id/recipients_editor_stub"
android:layout_width="match_parent"
android:layout_height="45dip"
android:layout="@layout/recipients_editor" />

ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub);
if (stub != null) {
View stubView = stub.inflate();
mRecipientsEditor = (RecipientsEditor) stubView.findViewById(R.id.recipients_editor);
mRecipientsPicker = (ImageButton) stubView.findViewById(R.id.recipients_picker);
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.