onTouch事件无法正常工作

use*_*676 2 android android-layout

我试图扩展相对布局,并添加一个简单的方法来设置onTouchListener.

问题是在我设置监听器之后,唯一被调用的事件是 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;
                }
            }
        });

    }

}
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

这是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();
    }

}
Run Code Online (Sandbox Code Playgroud)

从logcat打印MotionEvent动作时我得到0:

onTouch event called 0

Dan*_* L. 6

问题是,在行动之后你会回来false.把它转到true然后它也将通过其他事件.