分享

Android : holder.getSurface() always return null

 mandrave 2012-08-22

My view is a bunch of normal widget and a surfaceview. I don't know why after I get surfaceholder of SurfaceView and use getSurface() again on holder, I will always return null.

Here is my example code :

public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView
(R.layout.view);
   
}

   
@Override
   
public void onResume() {
       
super.onResume();
        surface
= (SurfaceView) findViewById(R.id.surfaceView);
       
this.holder = surface.getHolder();

         
if (holder.getSurface().isValid()){  // get surface again
             
Log.i("Notice","Surface holder is valid");
         
}
         
else
             
Log.i("Notice","Surface holder ISNOT valid");  //Always receive this
       
}

When I see Android document for getSurface() method. This is how it say:

Direct access to the surface object. The Surface may not always be available -- for example when using a SurfaceView the holder's Surface is not created until the view has been attached to the window manager and performed a layout in order to determine the dimensions and screen position of the Surface. You will thus usually need to implement Callback.surfaceCreated to find out when the Surface is available for use.

I don't understand this so much but I know I have miss something. Please explain for me, and tell me about Callback.surfaceCreated means, and how to implement it ?

Thanks :)

 

=============================================================================================

You are trying to use surface when it is not available yet. That's alright it is not available at yourActivity.onCreate or Activity.onResume methods because actually surface is placed in separate window behind your Activity window and has own lifecycle. You need to implementSurfaceHolder.Callback to receive events about Surface availability and do drawing from a separate thread. Look at LunarLander project in Android SDK samples folder, it is shown there how to use SurfaceView properly.

Your callback will look something like that:

public class MyCallback implements SurfaceHolder.Callback {
   
@Override
   
public void surfaceChanged(SurfaceHolder holder, int format,
       
int width, int height) {    
   
}

   
@Override
   
public void surfaceCreated(SurfaceHolder holder) {
       
// you need to start your drawing thread here
   
}

   
@Override
   
public void surfaceDestroyed(SurfaceHolder holder) {  
       
// and here you need to stop it
   
}
}

And than you need to set this callback to SurfaceHolder:

surface.getHolder().addCallback(new MyCallback());

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多