2014-12-05 77 views
0

我寫了一些代碼來從ImageView中獲取位置。下面是我的代碼:如何在MotionEvent的參數中添加

private void touchLocation(MotionEvent e){ 
float x = e.getX(); 
float y = e.getY(); 

String message = "Location is x = " + x + ", y = " + y "."; 

Context context = getApplicationContext(); 
int duration = Toast.LENGTH_LONG: 

Toast toast = Toast.makeText(context, message, duration); 
toast.show(); 

}

在onCreate()方法,如何將我調用這個函數?任何建議,非常感謝。我應該如何用類MotionEvent實例化一個對象?

回答

1
imageView.setOnTouchListener(new OnTouchListener(){ 

    @Override 
    public boolean onTouch(View v, MotionEvent e) { 

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

    String message = "Location is x = " + x + ", y = " + y "."; 

    // more code 

    return true; 
    } 
}); 
+0

我得到錯誤「類型View中的方法setOnTouchListener(View.OnTouchListener)不適用於參數(new OnTouchListener(){})」。爲什麼?以及如何解決它? – 2014-12-05 19:14:23

+0

確保您正確導入了偵聽器,您需要在其他導入文件的頂部導入「android.view.View.OnTouchListener;'。 – 2014-12-05 19:18:41

+0

感謝Petr Duchek。它解決了所有問題。 – 2014-12-05 19:23:59