从布局XML画SurfaceView [英] Draw SurfaceView from layout xml

查看:245
本文介绍了从布局XML画SurfaceView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于SurfaceView这是我从code成功了,我可以覆盖的OnDraw()方法。 但如何覆盖从它在布局XML定义的SurfaceView是的OnDraw()方法?反正是有访问draw()方法?

for a SurfaceView which I made it from code, i could override onDraw() method. but how to override that onDraw() method from a SurfaceView which is defined in layout XML? is there anyway to access the draw() method?

推荐答案

您不能访问声明,并添加到布局像这样的SurfaceView实例的OnDraw法:

You cannot access the onDraw-method of a SurfaceView instance declared and added to the layout like this:

<SurfaceView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

声明上面创建android.view.SurfaceView的实例,并把它添加到您的布局。你不能改变在该实例中的任何比你更可以改变在任何其他已编译的类code /行为的OnDraw法的行为。

The declaration above creates an instance of android.view.SurfaceView and adds it to your layout. You cannot change the behavior of the onDraw-method on that instance any more than you can change code/behaviour in any other already compiled class.

要达到你所要求的,你可以创建自己的SurfaceView的子类:

To achieve what you are asking for, you can create your own subclass of SurfaceView:

package myapp.views;

import android.view.SurfaceView;

public MySurfaceView extends SurfaceView implements Callback {
   ...
}

然后,以添加到您的布局,而不是一部开拓创新的香草SurfaceView,您只需参考类的全名作为您的布局XML元素:

And then, to add that to your layout instead of the orignal vanilla SurfaceView, you simply refer to the fully qualified name of your class as an XML element in your layout:

<myapp.views.MySurfaceView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

您SurfaceView子类必须声明一个构造函数上下文的AttributeSet 作为参数。而且不要忘了,你的表面观应实施 SurfaceHolder.Callback 并注册自己的SurfaceHolder:

Your SurfaceView subclass must declare a constructor that takes Context and AttributeSet as parameters. And don't forget that your surface view should implement SurfaceHolder.Callback and register itself to its SurfaceHolder:

public MySurfaceView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    getHolder().addCallback(this);
}

在画法将不会被自动调用,但可以确保你的观点的intial状态时,表面观初始化绘制。回调将作出 surfaceCreated 在这里,你可以调用draw-方法:

The draw-method will not be called automatically, but you can make sure that the intial state of your view is drawn when the surface view is initialized. A callback will be made to surfaceCreated where you can call the draw-method:

public void surfaceCreated(SurfaceHolder holder) {
    Canvas c = getHolder().lockCanvas();
    draw(c);
    getHolder().unlockCanvasAndPost(c);
}

瞧!

这篇关于从布局XML画SurfaceView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆