Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決 Android 切換到 SurfaceView 時黑屏閃屏與移動黑屏問題

編輯:關於 Android 程式設計

前陣子的專案裡,某個 Activity 採用 Fragment + ViewPager 結構,其中一個 Fragment 負責播放影片,用到了 SurfaceView。結果每次第一次進入該頁面都會黑屏閃一下。問題根源就在 SurfaceView 的特殊性。

為什麼會黑屏

國外開發者的分析說得很清楚:

I think I found the reason for the black flash. In my case I'm using a SurfaceView inside a Fragment and dynamically adding this fragment to the activity after some action. The moment when I add the fragment to the activity, the screen flashes black. I checked out grepcode for the SurfaceView source and here's what I found: when the surface view appears in the window the very fist time, it requests the window's parameters changing by calling a private IWindowSession.relayout(..) method. This method “gives” you a new frame, window, and window surface. I think the screen blinks right at that moment.
  The solution is pretty simple: if your window already has appropriate parameters it will not refresh all the window's stuff and the screen will not blink. The simplest solution is to add a 0px height plain SurfaceView to the first layout of your activity. This will recreate the window before the activity is shown on the screen, and when you set your second layout it will just continue using the window with the current parameters. I hope this helps.

原因歸納:

SurfaceView 有別於一般 View,它擁有獨立的緩衝與資料存取機制,系統對它的處理方式也不同。當 SurfaceView 第一次被加入某個 Activity 時,系統會請 WindowManager 重新配置版面(relayout),這個過程就會黑一下。由於只發生在第一次,後續再加 SurfaceView 就不會再黑屏了。

解法:

在真正需要 SurfaceView 之前,先讓它「提前出現一次」。最簡單的做法是在啟動頁或 Loading 頁的版面檔中放一個寬高都設為 0dp 的 SurfaceView——它不會影響版面配置,卻足以讓系統提前完成 window 的建立與配置。等到真正用到 SurfaceView 時,就不會再閃屏。

ViewPager 中的移動黑屏問題

另一個常見狀況是:ViewPager 裡用 SurfaceView 播影片,左右滑動時畫面會出現黑塊並跟著移動。這是因為 SurfaceView 的 Z 軸排序與一般 View 不同所致,解法是把它提到最上層並設為透明:

解法:

surfaceview.setZorderTop(true);

surfaceview.getHolder().setFormat(SurfaceView.TRANSPARENT);

補充說明:setZorderTop(true) 會讓 Surface 蓋在視窗之上,代價是它會遮住其他 View,因此不適合需要在其上疊加控制項的場景;這種情況改用 setZOrderMediaOverlay(true) 通常更合適。若使用 TextureView 替代 SurfaceView,則能完全避開這類 Z 軸排序與閃屏問題,效能代價換取行為一致性,值得權衡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved