2017-09-24 55 views
-1

觸摸事件和手勢事件,我想觸摸監聽器設置並在觸摸右如何處理在屏幕上

使用建立方法我設置觸摸監聽器爲主要佈局

mainActivityLayout.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       return true; 
      } 
     }); 

XML文件:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/mainActivityLayout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/colorBackground" 
    android:orientation="vertical" 
    android:clickable="true" 
    android:focusable="true" 
    android:focusableInTouchMode="true"> 

然後覆蓋的onTouchEvent,但沒有工作

@Override 
    public boolean onTouchEvent(MotionEvent event) { 
     Toast.makeText(getBaseContext(), "On Touch", Toast.LENGTH_SHORT).show(); 

     if (event.getAction() == *TouchRight*) 
      Toast.makeText(getBaseContext(), "Touch Right", Toast.LENGTH_SHORT).show(); 
     return super.onTouchEvent(event); 
    } 

我如何處理手勢事件?

+0

這意味着你在根佈局上設置觸摸監聽器? –

+0

@AbdulWaheed是的,我想爲屏幕的所有區域設置 – Bahadori

+0

我已經更新了我的答案將這些xml屬性添加到您的主父佈局這將爲你工作 –

回答

0

您可以使用下面的代碼示例

float initialX, initialY; 

@Override 
public boolean onTouchEvent(MotionEvent event) { 

int action = event.getActionMasked(); 

switch (action) { 

    case MotionEvent.ACTION_DOWN: 
     initialX = event.getX(); 
     initialY = event.getY(); 

     Log.d(TAG, "Action was DOWN"); 
     break; 

    case MotionEvent.ACTION_MOVE: 
     Log.d(TAG, "Action was MOVE"); 
     break; 

    case MotionEvent.ACTION_UP: 
     float finalX = event.getX(); 
     float finalY = event.getY(); 

     Log.d(TAG, "Action was UP"); 

     if (initialX < finalX) { 
      Log.d(TAG, "Left to Right swipe performed"); 
     } 

     if (initialX > finalX) { 
      Log.d(TAG, "Right to Left swipe performed"); 
     } 

     if (initialY < finalY) { 
      Log.d(TAG, "Up to Down swipe performed"); 
     } 

     if (initialY > finalY) { 
      Log.d(TAG, "Down to Up swipe performed"); 
     } 

     break; 

    case MotionEvent.ACTION_CANCEL: 
     Log.d(TAG,"Action was CANCEL"); 
     break; 

    case MotionEvent.ACTION_OUTSIDE: 
     Log.d(TAG, "Movement occurred outside bounds of current screen element"); 
     break; 
} 

return super.onTouchEvent(event); 
} 

。希望回答的問題 編輯 對於你的父母佈局工作下面的代碼添加到您的父母佈局像相對佈局

 android:clickable="true" 
    android:focusable="true" 
    android:focusableInTouchMode="true" 
+0

永不會叫!而登錄貓是空的! – Bahadori

+0

在你的代碼中,你顯示敬酒是爲你工作? –

+0

不,在我的代碼和你的代碼中,OnTouchEvent永遠不會調用 – Bahadori