需求:App 啟動顯示歡迎圖 2 秒,期間 WebView 靜默加載主頁 URL,2 秒後隱藏歡迎圖顯示已加載好的網頁,無白屏等待。
若用兩個 Activity(WelcomeActivity → MainActivity),MainActivity 的 onCreate 必須等 WelcomeActivity finish() 後才執行,**無法實現並行預加載**。
<FrameLayout xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/iv_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/splash_bg" />
</FrameLayout>
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ImageView ivSplash;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
ivSplash = findViewById(R.id.iv_splash);
// 1. WebView 配置並開始加載
WebSettings ws = webView.getSettings();
ws.setJavaScriptEnabled(true);
ws.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient()); // 內部跳轉不打開瀏覽器
webView.loadUrl("https://example.com"); // 靜默加載
// 2. 2 秒後淡出歡迎圖
ivSplash.postDelayed(() -> {
ivSplash.animate().alpha(0f).setDuration(300)
.withEndAction(() -> ivSplash.setVisibility(View.GONE))
.start();
}, 2000);
}
@Override
public void onBackPressed() {
if (webView.canGoBack()) webView.goBack();
else super.onBackPressed();
}
}
setWebViewClient 必須在 loadUrl 前設置。animate().alpha(0) 比直接 GONE 自然。onDestroy 裡 webView.destroy() 防內存洩漏。webView.setWebViewClient(new WebViewClient() {
@Override public void onPageFinished(WebView view, String url) {
// 頁面加載完成,若還在 2 秒內,等時間到再切;若已過 2 秒,立即切
if (splashVisible) startFadeOut();
}
});
單 Activity 疊加預加載模式,同時解決「啟動速度感知」與「網頁加載等待」兩大體驗痛點,是混合開發標準範式。