写这一篇文章之前我看了好多遍事件分发机制的流程,并且来自不同的书籍,但始终无法记住事件分发流程。
于是我写了一个demo分析事件分发的流程,目的为了找到事件分发机制的规律方便记忆。
以下是总结的规律,如果错误请及时举报,说到底有些东西还得亲手试试才能弄明白
规律:
dispatchTouchEvent.
true 不在向下一级view分发事件,停止
false 向上Activity的onTouchEvent
执行super方法 向同一个View的onInterceptTouchEvent或者onTouchEvent传递或者下一个View的dispatchTouchEvent传递
onInterceptTouchEvent
true 表示拦截,执行该View的onTouchEvent
false 和执行super方法表示不拦截执行下一个view的dispatchTouchEvent
onTouchEvent
true 和super 消费此事件
false 把事件抛向Activity onTouchEvent
流程图
代码示例:
public class MyTextView extends android.support.v7.widget.AppCompatTextView {
private static final String TAG = "MyTextView";
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d(TAG,"dispatchTouchEvent");
return true;
//return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG,"onTouchEvent");
//return true;
return super.onTouchEvent(event);
}
}
public class MyLinearLayout extends LinearLayout {
private static final String TAG = "MyLinearLayout";
public MyLinearLayout(Context context) {
super(context);
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d(TAG,"dispatchTouchEvent");
//return false;
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d(TAG,"onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
//return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG,"onTouchEvent");
return super.onTouchEvent(event);
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.mytextview);
textView.setOnClickListener(this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("MainActivity","dispatchTouchEvent");
//return false;
return super.dispatchTouchEvent(ev);
}
@Override
public void onUserInteraction() {
//Log.d("MainActivity","onUserInteraction");
//return true;
super.onUserInteraction();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("MainActivity","onTouchEvent");
//return true;
return super.onTouchEvent(event);
}
@Override
public void onClick(View v) {
Log.d("MainActivity","onClick");
}
}