Touch事件分发中有两个主角:ViewGroup和View。
为了方便理解,今天我们先单独讲View的Touch事件分发,我们先看下实例代码
首先,我们自定义一个view
public class TouchView extends View {
private Context context;
private AttributeSet attrs;
public TouchView(Context context) {
super(context);
}
public TouchView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.attrs = attrs;
}
public TouchView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
addTextView("onTouchEvent-->"+event.getAction(),(LinearLayout)getParent());
return super.onTouchEvent(event);
}
/**
* 用来做事件分发
* @param event
* @return
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
addTextView("dispatchTouchEvent-->"+event.getAction(),(LinearLayout)getParent());
return super.dispatchTouchEvent(event);
}
public void addTextView(String tag, ViewGroup viewGroup){
TextView textView=new TextView(context);
textView.setText(tag);
textView.setTextSize(18);
textView.setTextColor(Color.BLACK);
viewGroup.addView(textView);
TextView text=new TextView(context);
text.setText("↓");
viewGroup.addView(text);
}
}
more >>