2017-09-24 51 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