使用MySurfaceView和main.xml(android)

时间:2011-11-16 09:18:53

标签: android surfaceview

我在android上有一个简单的程序,用户触摸。

这是主要活动:

public class DrawingActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //setContentView(new MySurfaceView(this)); - this way it works, but 
                                          // i'm interseted in previous
}
}

这是main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.shchurov.MySurfaceView  
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:id="@+id/msv" 
/>
</LinearLayout>

这是MySurfaceView类:

public class MySurfaceView extends SurfaceView 
            implements SurfaceHolder.Callback {

private SurfaceHolder surfaceHolder;
Canvas canvas=null;
Paint paint=new Paint();


public MySurfaceView(Context context) {
    super(context);
    getHolder().addCallback(this);
    paint.setColor(Color.GREEN);
    paint.setStyle(Style.FILL);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {   
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    this.surfaceHolder=holder;
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}

public boolean onTouchEvent(MotionEvent event)
{
    canvas=surfaceHolder.lockCanvas(null);
    canvas.drawCircle(event.getX(), event.getY(), 10, paint);
    surfaceHolder.unlockCanvasAndPost(canvas);
    return true;
}

}

包是对的,但由于某些原因它不起作用,任何人都可以帮忙吗?

更新:如果我将MySurfaceView更改为此示例,那么它可以工作:

public class MySurfaceView extends View 
{
Paint paint;
public SomeView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    paint = new Paint();
    paint.setColor(Color.YELLOW);
    paint.setStyle(Style.FILL);
}

@Override
protected void onDraw(Canvas canvas)
{
    canvas.drawCircle(20, 20, 20, paint);
}
}

2 个答案:

答案 0 :(得分:1)

layout_width = “FILL_PARENT”

layout_height = “FILL_PARENT”

在surfaceview标签内

可以解决您的问题。

答案 1 :(得分:0)

您需要/应该实现视图可以拥有的所有三个构造函数:

//Simple constructor to use when creating a view from code.
View(Context context)

//Constructor that is called when inflating a view from XML.
View(Context context, AttributeSet attrs)

//Perform inflation from XML and apply a class-specific base style.
View(Context context, AttributeSet attrs, int defStyle)

这只是从View class constructor details in the documentation复制而来。