在xml中链接嵌套的SurfaceView类

时间:2013-05-28 06:28:56

标签: android xml android-layout surfaceview

我在类中扩展了SurfaceView,如下所示:

MainActivity.java

public class MainActivity extends Activity implements OnTouchListener {

    SurfaceTest mySurface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.surface);
        mySurface = (SurfaceTest) findViewById(R.layout.surface);
        mySurface.setOnTouchListener(this);
    }
    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub
        // ... some code ...
        return true;
    }
    public class SurfaceTest extends SurfaceView implements Runnable {

        SurfaceHolder myHolder;

        public SurfaceTest(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            myHolder = getHolder();
        }

        public SurfaceTest(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
            myHolder = getHolder();
        }

        public SurfaceTest(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            // TODO Auto-generated constructor stub
            myHolder = getHolder();
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                if (!myHolder.getSurface().isValid()) {
                    continue;
                }
                Canvas canvas = myHolder.lockCanvas();
                //...some code...
                myHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

surface.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <com.example.testsurfaceview.MainActivity.SurfaceTest
        android:id="@+id/surfaceView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</FrameLayout>

我在此xml文件的图形布局中有错误

"The following classes could not be instantiated:
- com.example.testsurfaceview.MainActivity.SurfaceTest"

一个可行的解决方案是为SurfaceTest类创建新类,然后在xml文件中使用com.example.testsurfaceview.SurfaceTest

但问题是我使用onTouch事件中的大量信息,用于在run()方法中绘制画布。这就是我在SurfaceTest

中实施MainActivity课程的原因

所以我现在有两个选择:

1)使xml适用于嵌套的SurfaceTest类 2)创建新的SurfaceTest类并使用Intent传递在onTouch中获得的所有信息。

你有什么建议?

1 个答案:

答案 0 :(得分:1)

在包中创建一个名为SurfaceTest的其他类文件,然后将其添加到xml文件中。它肯定会奏效。将onDraw(Canvas canvas)onTouchEvent(MotionEvent event)添加到Surface View class