Android佈局優化
使用標籤來合併佈局
當父佈局是FrameLayout的時候,我們就可以用這個標籤將我們自己的父佈局和系統Activity提供的視圖FrameLayout進行合併,這樣就會減少一層佈局嵌套
使用時直接將FrameLayout替換成標籤即可
使用標籤重用佈局
使用場景
多次使用相同的佈局
佈局有一個通用的組成部分
佈局依賴於設備配置比如橫豎屏切換
使用方式:代碼也很簡單創建將要被重用的佈局children.xml;然後在想要重用children.xml的地方引入:
<include android:id="@+id/inLayout"
android:layout="@layout/children">
ViewStub
ViewStub採用了推遲初始化技術,它可以推遲實例化提高性能,並且如果不觸發初始化的話就不會初始化會節省這部分的內存
ViewStub是一個輕量級不可見的視圖。
使用:
<FrameLayout 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="com.android.test.TestAnsyActivity">
<ViewStub
android:id="@+id/mystub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/stub_layout" />
如代碼所示,佈局被展開時,只有一個子視圖mystub,mystub引用了一個佈局stub_layout,即使stub_layout很複雜展開很費時間都沒關係,都不會影響視圖的展開效率,因爲此時stub_layout佈局無需展開.
那怎麼展開ViewStub佈局呢
方式一:
ViewStub stub = (ViewStub) findViewById(R.id.mystub);
View inflatedView = stub.inflate();
方式二:
View view = findViewById(R.id.mystub);
view.setVisibility(View.VISIBLE);
view = findViewById(R.id.myid);
不過,儘可能的減少findViewById()的使用,如下:
View view = findViewById(R.id.mystub);
view.setVisibility(View.VISIBLE);
if (view.getParent() == null) {
view = findViewById(R.id.myid);
} else {
}