編輯:關於 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 裡用 SurfaceView 播影片,左右滑動時畫面會出現黑塊並跟著移動。這是因為 SurfaceView 的 Z 軸排序與一般 View 不同所致,解法是把它提到最上層並設為透明:
解法:
surfaceview.setZorderTop(true);
surfaceview.getHolder().setFormat(SurfaceView.TRANSPARENT);
補充說明:setZorderTop(true) 會讓 Surface 蓋在視窗之上,代價是它會遮住其他 View,因此不適合需要在其上疊加控制項的場景;這種情況改用 setZOrderMediaOverlay(true) 通常更合適。若使用 TextureView 替代 SurfaceView,則能完全避開這類 Z 軸排序與閃屏問題,效能代價換取行為一致性,值得權衡。
Android 進階:SQLite 分頁讀取的實作細節
Android 本身就內建了嵌入式領域常用的 SQLite,省下了自行移植安裝的功夫。SQLite 支援大部分 SQL92 標準,日常用得到的語句幾乎都能跑;除此之外,A
圖文教程:在 Android Studio 中接入 GitHub 完成首次推送
第一步:在 GitHub 上創建倉庫 登錄 GitHub,點擊右上角「+」,選擇 New repository。 填寫表單,新建名為 testproject 的倉庫,並
Android 自定義 View 實戰:Bitmap 圖像處理與 Matrix 變換全解
一、先認識 Bitmap Bitmap 就是「位圖」,常見副檔名為 .bmp 或 .dib。它是 Windows 平台上最老牌的圖形格式之一,核心概念是把一張圖想成由無數
從源碼徹底搞懂 Android 事件分發機制
事件分發在 Android 裡舉足輕重。滑動衝突、下拉刷新、嵌套滑動,任何一個場景都需要你把分發機制想得足夠透徹,才能寫出正確的處理邏輯。我曾經以為自己已經很清楚了,也寫