2013-06-25 125 views
2

我想扩展相对布局,并添加一个简单的方法来设置onTouchListener。onTouch事件无法正常工作

的问题是,当我设置的听众,也就是被称为唯一的事件是MotionEvent.ACTION_DOWN

其他事件都不会被调用。

这里是我的自定义相对布局的代码:

public class MyRelativeLayout extends RelativeLayout { 

    public MyRelativeLayout(Context context) { 
     super(context); 
    } 

    public MyRelativeLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    public void setOnTouchEvent() { 
     this.setOnTouchListener(new OnTouchListener() { 

      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       Log.d("myTextView", "onTouch event called"); 
       switch (event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        //only this event is being called 
        return false; 
       default: 
        //other events are not being called 
        return false; 
       } 
      } 
     }); 

    } 

} 

下面是XML代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

    <com.example.ontouchtest.MyRelativeLayout 
     android:id="@+id/test" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:text="@string/hello_world" /> 

</RelativeLayout> 

这是在MainActivity:

public class MainActivity extends Activity { 
    MyRelativeLayout test; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     test = (MyRelativeLayout) findViewById(R.id.test); 
     test.setOnTouchEvent(); 
    } 

} 

从logcat的当打印MotionEvent时,我得到0:

onTouch event called 0

+0

改为Log.d(“myTextView”,“onTouch event called”);打印行为并附加它。 –

+0

@Daniel它打印'0' – user1940676

回答

6

问题是,行动结束后,您将返回false。把它变成true然后它也会通过其他事件。

+0

是啊,我看到http://android-developers.blogspot.co.il/2010/06/making-sense-of-multitouch.html 谢谢你的例子。 – user1940676