I have a class inside a class that extends SurfaceView like this:
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>
I have an error in Graphical Layout of this xml file saying
"The following classes could not be instantiated:
- com.example.testsurfaceview.MainActivity.SurfaceTest"
One possible solution that worked for me was to create new class for SurfaceTest
class and then using com.example.testsurfaceview.SurfaceTest
in xml file.
But the problem again is I use a lot of information from onTouch
event which is used to draw on canvas in run()
method. This is the reason I implemented SurfaceTest
class inside MainActivity
So I have two choices right now:
1) make xml work for nested SurfaceTest class
2) create new SurfaceTest class and pass all the info obtained in onTouch
using an Intent.
What do you suggest?