触控方法SurfaceView Android无法正常工作

时间:2016-10-12 17:12:56

标签: java android surfaceview ontouchevent

我创建了一个SurfaceView(您可以在下面看到它)并从我的主要活动开始。我在SurfaceView中覆盖了onTouchEvent方法,问题是我想用Log.d记录的数据没有记录,我没有收到任何消息...... 有谁知道如何解决这个问题?

我的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) {

}

}

我的主要活动:

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()));

}
}

1 个答案:

答案 0 :(得分:0)

尝试在以下部分代码中将“getApplicationContext()”更改为“this”:

setContentView(new MainGamePanel(getApplicationContext()));

setContentView(new MainGamePanel(this));