domiauli domiauli - 1 month ago 7
Android Question

On Touch Method SurfaceView Android doesn't work

I created a SurfaceView (you can see it in the following) and started in from my Main Activity. I overwrote the onTouchEvent method in the SurfaceView and the problem is that the data I want to have logged with Log.d isn't logged, I don't get any Message...
Does anyone have an idea how I can fix this?

My SurfaceView:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;





public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {

private float top;
private float left;
private float bottom;
private float right;

private MainThread thread;

MainGamePanel(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
setFocusable(true);
}


@Override
public void surfaceCreated(SurfaceHolder holder) {
setWillNotDraw(false);
thread.setRunningMode(MainThread.RUNNING);
thread.start();
}

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

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (Exception e) {
}
}
}


@Override
public boolean onTouchEvent(MotionEvent event) {

float x = event.getX();
float y = event.getY();

right = x + 30;
left = x - 30;
top = y - 30;
bottom = y + 30;

Log.d("tag", x + " " + y);

return true;
}

@Override
protected void onDraw(Canvas canvas) {

}

}


My Main Activity:

import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;



public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(new MainGamePanel(getApplicationContext()));

}
}

Answer

Try changing "getApplicationContext()" to "this" in following part of code:

setContentView(new MainGamePanel(getApplicationContext()));

to

setContentView(new MainGamePanel(this));