天天看點

Android如何避免切換至SurfaceView時閃屏(黑屏閃一下)以及黑屏移動問題

轉至 https://www.cnblogs.com/Joanna-Yan/p/4829325.html

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);

作者:Joanna.Yan

出處:http://www.cnblogs.com/Joanna-Yan/

本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連結,否則保留追究法律責任的權利。