Add SurfaceView flash a black screen(动态添加SurfaceView导致黑一下屏)

 

将一个SurfaceView动态添加到一个View上,发现会闪一下黑屏。有以下两种方式解决。

 

 为了查这个问题,只好开启WindowManagerService的debug模式,查看log,发现window的格式和SurfaceView的格式不一样,被销毁重建了。于是我在activity onCreate方法里面,设置window和SurfaceView的格式,解决了这个问题,代码如下:

getWindow().setFormat(PixelFormat.TRANSLUCENT); //在fragment中使用在getWindow前加getActivity()

 

 

   参考: http://stackoverflow.com/questions/8772862/surfaceview-flashes-black-on-load

  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 第一次在 Window 里面显示的时候,会触发 IWindowSession.relayout(…) 方法,该方法会 relayout 整个布局,导致屏幕黑屏一下。解决方案,就是在 Activity 加入一个默认就显示的 SurfaceView,可以通过设置它的宽度为 0,来避免用户看见它。这样在 Fragment 里面的 SurfaceView 就已经是第二个 SurfaceView 了。可以重用上一个 SurfaceView 的参数,避免的明显的屏幕黑屏。

posted @ 2015-10-05 18:47  oho_yoho  阅读(760)  评论(0)    收藏  举报