1.最近的項目中,有一個Activity用到Fragment+ViewPager,其中一個fragment中實現了視頻播放的功能,包含有SurfaceView。結果,每次打開程序第一次進入到該Activity時都會閃屏黑一下。原因就出在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界面)的時候,在其它界面的layout.xml文件中添加一個SurfaceView,寬和高都弄成0dp,這樣對布局沒影響,而且這個東西使得surfaceview第一次出現了,那么也就是說,下一次我們真正用到SurfaceView的時候就不會閃屏了。
2.viewpager中有surfaceview播放視頻,來回滑屏時,關於黑屏移動問題
解決:
surfaceview.setZorderTop(true);
surfaceview.getHolder().setFormat(SurfaceView.TRANSPARENT);
如果此文對您有幫助,微信打賞我一下吧~