2

我正在尝试扩展相对布局,并添加一个简单的方法来设置 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;
                }
            }
        });

    }

}

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

}

在打印动作时从 logcatMotionEvent我得到 0:

onTouch event called 0

4

1 回答 1

6

问题是行动下来后你返回false。把它转到true,然后它也会通过其他事件。

于 2013-06-25T07:21:44.960 回答