如何在Android中使用View Stub?
在進入示例之前,我們應該瞭解Android中的View Stub是什麼。它是一個零大小的延遲載入檢視。它將在執行時載入。使用inflate()方法,它將在執行時載入並新增到視窗管理器或檢視組中。使用setVisibility(int),我們可以顯示和隱藏Android中的View Stub。
此示例演示如何在Android中使用View Stub。
步驟1 - 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟2 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:id="@+id/layout" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="show"/> <Button android:id="@+id/hide" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hide"/> <ViewStub android:id="@+id/viewStub" android:layout_width="match_parent" android:layout="@layout/childlayout" android:layout_height="300dip" > </ViewStub> </LinearLayout>
在上面的程式碼中,我們建立了兩個按鈕“顯示”和“隱藏”。它將根據我們的需求顯示和隱藏View Stub佈局。接下來,我們宣告View Stub並載入佈局,如下所示:
android:layout="@layout/childlayout"
上面的程式碼表明,我們已將子佈局載入到View Stub中。當您將子佈局宣告到View Stub時,它不會自動載入。我們必須在Activity類中呼叫inflate方法。
步驟3 - 將以下程式碼新增到src/MainActivity.java
package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@TargetApi(Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewStub viewStub = findViewById(R.id.viewStub);
viewStub.inflate();
Button show = findViewById(R.id.show);
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewStub.setVisibility(View.VISIBLE);
}
});
Button hide = findViewById(R.id.hide);
hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewStub.setVisibility(View.GONE);
}
});
}
}在上面的程式碼中,我們宣告View Stub並載入View Stub,如下所示:
final ViewStub viewStub = findViewById(R.id.viewStub); viewStub.inflate();
單擊“顯示”按鈕,它將顯示View Stub。現在單擊“隱藏”按鈕,它將隱藏View Stub。
步驟4 - 無需更改manifest.xml。
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要在Android Studio中執行應用程式,請開啟專案中的一個Activity檔案,然後單擊工具欄中的執行圖示
。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕。

最初,它將顯示如上所示,當您單擊“隱藏”按鈕時,它將消失,如下所示:

現在單擊“顯示”按鈕,它將顯示ImageView,如下所示:

點選這裡下載專案程式碼
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP