【问题标题】:Android SurfaceView not responding to touch eventsAndroid SurfaceView 不响应触摸事件
【发布时间】:2015-03-11 14:29:47
【问题描述】:

我试图获得一个简单的表面视图来响应触摸事件。下面的应用程序启动但不响应触摸事件。我有一个 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);
    }

}

这是表面视图类

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;
    }

}

【问题讨论】:

    标签: android surfaceview


    【解决方案1】:
    1. 删除implements OnTouchListener
    2. onTouch(View v, MotionEvent event) 更改为onTouchEvent(MotionEvent event)

    它不工作的原因是 SurfaceView 不知道它应该是它自己的 OnTouchListener 没有你告诉它。或者,您可以通过将此代码添加到您的 onCreate() 来使其工作:

    mySurface = new MainSurface(this);
    mySurface.setOnTouchListener(mySurface);
    

    不过,由于 SurfaceView 已经有一个 OnTouchEvent 函数,所以使用它会更简单。

    另外,不要将 SurfaceView 声明为静态的。

    【讨论】:

    • 您的编辑做到了。谢谢。你知道为什么它不能作为一个实现吗?只是想更好地理解一点。
    • 我不知道为什么 onTouchEvent() 方法不适合你,我刚刚试了一下,它对我有用。如上所述,onTouch() 方式需要 setOnTouchListener()。
    【解决方案2】:

    您应该在触摸事件中识别Action,例如:

     @Override
    public boolean onTouch(View v, MotionEvent event) {
    
    int action = event.getAction();
    switch(action){
    
    case MotionEvent.ACTION_DOWN:
    break;
    
    case MotionEvent.ACTION_MOVE:
    break;
    
    case MotionEvent.ACTION_UP:
    
    break;
    
    case MotionEvent.ACTION_CANCEL:
    break;
    
    case MotionEvent.ACTION_OUTSIDE:
    break;
     }
      return true;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多