BPo*_*Poy 2 android surfaceview
我试图获得一个简单的表面视图来响应触摸事件.下面的应用程序启动但不响应触摸事件.我有一个Log.i语句来确认(通过打印到控制台)触摸事件是否正常工作.谁能告诉我我做错了什么?
这是我的主要活动
public class MainActivity extends Activity {
public static int screenWidth, screenHeight;
public static boolean running=true;
public static MainSurface mySurface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this gets the size of the screen
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenWidth = displaymetrics.widthPixels;
screenHeight = displaymetrics.heightPixels;
Log.i("MainActivity", Integer.toString(screenWidth) + " " + Integer.toString(screenHeight));
mySurface = new MainSurface(this);
setContentView(mySurface);
}
}
Run Code Online (Sandbox Code Playgroud)
这是表面视图类
public class MainSurface extends SurfaceView implements OnTouchListener {
public MainSurface(Context context) {
super(context);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
int point = event.getPointerCount();
Log.i("MainSurface", Integer.toString(x)); //nothing prints to the console here
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
implements OnTouchListener
.onTouch(View v, MotionEvent event)
到onTouchEvent(MotionEvent event)
.它不起作用的原因是SurfaceView不知道它应该是它自己的OnTouchListener而不告诉它.或者,您可以通过将此代码添加到onCreate()来使其工作:
mySurface = new MainSurface(this);
mySurface.setOnTouchListener(mySurface);
Run Code Online (Sandbox Code Playgroud)
但是,由于SurfaceView已经具有OnTouchEvent函数,因此使用它更简单.
另外,不要将SurfaceView声明为静态.