編輯:關於 Android 程式設計
ViewStub 能把一個布局檔的載入時機往後延,直到真正需要時才 inflate,藉此加快初次顯示速度。
兩者都是把另一個布局檔嵌進來,但行為完全不同。include 會立即載入並佔用資源;ViewStub 本身是一個零尺寸的佔位元件,只有在你呼叫 inflate() 或把它設為可見時才會真正載入內容,而且載入後它自己會被替換掉。
這個特性很適合「不確定會不會用到」的區塊,例如錯誤提示、空資料狀態、展開式面板,或是依裝置尺寸動態決定要顯示哪個畫面。
主布局中放一個 ViewStub 標籤:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="顯示/隱藏" />
<ViewStub
android:id="@+id/vs"
android:inflatedId="@+id/inflated_id"
android:layout="@layout/view_stub_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
被延後載入的那份布局另存為 view_stub_layout.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="vs 中的 tv" />
</LinearLayout>
public class MainActivity extends ActionBarActivity {
private ViewStub stub;
private boolean isShow = true;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stub = (ViewStub) findViewById(R.id.vs);
// 兩種觸發方式:stub.inflate() 或 stub.setVisibility(View.VISIBLE)
stub.setVisibility(View.VISIBLE);
// inflatedId 指定的 id 會套用在載入後的根節點上
View root = findViewById(R.id.inflated_id);
// 必須先觸發載入,才找得到內部的控制項
tv = (TextView) root.findViewById(R.id.tv);
root.setBackgroundColor(Color.BLUE);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.toggle:
if (isShow) {
stub.setVisibility(View.GONE);
} else {
stub.setVisibility(View.VISIBLE);
tv.setText("---");
}
isShow = !isShow;
break;
default:
}
}
}
有兩個細節值得注意。第一,android:inflatedId 是 ViewStub 專屬的屬性,載入後會把這個 id 設到新布局的根節點上,讓外部能直接 findViewById 抓到它;若沒設這個屬性,就得改用 ViewStub 原本的 id 去取,而那個 id 在載入後已經失效。
第二,順序很重要——必須先觸發載入,才能取得內部的子控制項,反過來就會拿到 null。
最後,這裡用 setVisibility 來做顯示/隱藏其實有個副作用:ViewStub 一旦 inflate 完成就會從版面樹中被移除,後續再設 GONE 或 VISIBLE 都作用不到它身上,而是作用在它原本的位置。因此若需要反覆切換顯示狀態,比較穩妥的做法是保留 inflate 後的根節點,直接對那個 View 做 visibility 切換。
Android Support Design Library 常用控件入門(一)
Google 推出 Material Design 已經有一段時間了。為了讓開發者更容易做出符合材料設計的介面,官方提供了 Android Support Design
Android 仿京東金融首頁:隨捲動縮小的頭像效果
一、效果預覽 先看一下成果,GIF 錄製時有些卡頓,實際在真機上運行相當順暢。 二、實現方式 這個效果看起來有趣,原理其實很單純:只要監聽 ScrollView 在 Y
Activity 基礎全景整理:生命週期、Fragment、啟動模式與 Window/View 關係
一、Activity 生命週期 這張流程圖大家應該都不陌生。與其背誦,不如把常見操作對應到回撥鏈上來記: 操作場景回撥順序 啟動 ActivityonCreate
Android 4.4 狀態欄透明化與沉浸式效果實作
Android 4.4 之後,系統允許應用程式把狀態欄處理成半透明或全透明,讓下方內容延伸到系統列區域,形成更完整的沉浸式視覺。這種做法常用於首頁、相簿或視差捲動頁面。實