2010-06-29 27 views
9

现在我所要做的就是检测何时按下屏幕,然后显示日志消息以确认发生。到目前为止,我的代码已从CameraPreview示例代码(它最终会拍摄图片)中修改,因此大部分代码位于扩展SurfaceView的类中。来自SDK的示例代码的API是7.我如何在Android上检测触摸输入

回答

19

请尝试下面的代码来检测触摸事件。

mView.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     //show dialog here 
     return false; 
    } 
}); 

显示对话框使用活动方法showDialog(int)。你必须实现onCreateDialog()。详情请参阅文档。

4

我没有这样说:

public class ActivityWhatever extends Activity implements OnTouchListener 
{ 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.yourlayout); 

     //the whole screen becomes sensitive to touch 
     mLinearLayoutMain = (LinearLayout) findViewById(R.id.layout_main); 
     mLinearLayoutMain.setOnTouchListener(this); 
    } 

    public boolean onTouch(View v, MotionEvent event) 
    { 
     // TODO put code in here 

     return false;//false indicates the event is not consumed 
    } 
} 
在视图的XML

,注明:

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/layout_main"> 

    <!-- other widgets go here--> 

</LinearLayout> 
13

这里是如何检测一个简单的触摸事件一个简单的例子,让COORDS并举杯祝酒。这个例子中的事件是Action Down,Move和Action up。

import android.app.Activity; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

    private boolean isTouch = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 

     int X = (int) event.getX(); 
     int Y = (int) event.getY(); 
     int eventaction = event.getAction(); 

     switch (eventaction) { 
      case MotionEvent.ACTION_DOWN: 
       Toast.makeText(this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show(); 
       isTouch = true; 
       break; 

      case MotionEvent.ACTION_MOVE: 
       Toast.makeText(this, "MOVE "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show(); 
       break; 

      case MotionEvent.ACTION_UP: 
       Toast.makeText(this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show(); 
       break; 
     } 
     return true; 
    } 
}