我正在尝试扩展相对布局,并添加一个简单的方法来设置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();
}
}
从logcat打印MotionEvent
动作时我得到0:
onTouch event called 0
答案 0 :(得分:6)
问题是,在执行操作后,您将返回false
。将其转为true
,然后它也会传递其他事件。