【问题标题】:Draw SurfaceView from layout xml从布局 xml 绘制 SurfaceView
【发布时间】:2011-07-09 09:08:18
【问题描述】:

对于我从代码中创建的 SurfaceView,我可以覆盖 onDraw()
但是如何从布局 XML 中定义的 SurfaceView 覆盖 onDraw() 呢?有什么方法可以访问draw() 方法吗?

【问题讨论】:

    标签: android android-layout surfaceview


    【解决方案1】:

    您无法访问声明并添加到布局中的 SurfaceView 实例的 onDraw 方法,如下所示:

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

    上面的声明创建了一个 android.view.SurfaceView 的实例并将它添加到你的布局中。您无法更改该实例上的 onDraw 方法的行为,就像您无法更改任何其他已编译类中的代码/行为一样。

    要实现您的要求,您可以创建自己的 SurfaceView 子类:

    package myapp.views;
    
    import android.view.SurfaceView;
    
    public MySurfaceView extends SurfaceView implements Callback {
       ...
    }
    

    然后,要将其添加到您的布局而不是原始的香草 SurfaceView,您只需将类的完全限定名称作为布局中的 XML 元素引用:

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

    您的 SurfaceView 子类必须声明一个以 ContextAttributeSet 作为参数的构造函数。不要忘记你的表面视图应该实现SurfaceHolder.Callback并将自己注册到它的SurfaceHolder:

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

    draw-method 不会被自动调用,但您可以确保在初始化表面视图时绘制视图的初始状态。将向surfaceCreated 进行回调,您可以在其中调用绘图方法:

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

    瞧!

    【讨论】:

    • ok.. 如何在 xml 中引用我的类?我没有办法做到这一点?
    • 再看上面的XML sn-p。实际的 XML 元素是您的类的名称。不是很直观或 XML-ish,这是肯定的。
    • 我不明白?这是否意味着我必须“导入”我的包名之类的??
    • 您没有“导入”您的包名,您只需指出您自己的 SurfaceView 实现,它将被实例化并添加到您的布局中,而不是普通的 SurfaceView。我已经编辑了上面的答案以澄清这一点。我希望这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多