Surface View Tutorial
This tuturial guides in using surface view at a very basic level . The code presented in this tutorial creates a simple view with a image using a surface view instead of conventianal View object.
Create New Project & Activity
Lets create a new android project using ecilpse. Lets name it SurfaceExample and our activity name as SurfaceExampleActivity.
Add another class which will extend surface view. Lets name this class SurfacePanel.
The SurfacePanel class extends the surface view .
public class SurfacePanel extends SurfaceView
{
/** parameterized constructor for surface panel class**/
public SurfacePanel(Context context, AttributeSet attrSet)
{
super(context, attrSet);
}
}
Creating Xml with surface view class
Lets modify our main.xml layout file , and add surfacePanel class as its child.
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<com.study.surfaceExample.SurfacePanel
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
As shown in the above xml file, we have added our surface view class as part of xml file.
Now run the application . It gives a blank black screen.
Inorder to do some drawing in our surface view class , we can not use its onDraw function because even if we override the onDraw function then also the output will be same blank black screen.
This is because the onDraw function is not getting called itself.
To resolve this we will implement SurfaceHandler.Callback interface.This interface provides three methods related to surface creation, change and deletion.
To register the class itself as callback we will add the this pointer in add callback method in the constructor of our SurfacePanel class.
SurfaceView with callback interface
public class SurfacePanel extends SurfaceView implements SurfaceHolder.Callback
{
public SurfacePanel(Context ctx, AttributeSet attrSet)
{
super(ctx, attrSet);
context = ctx;
//the bitmap we wish to draw
mbitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.logintab_off);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
}