前言
在写应用时 ,布局中设置了一个button之后点击这个button,button的背景就会变化,我们什么都没干就有了这个效果,最近项目正好涉及到相关的绘制,就去源码里面看一下点击时的实现。关于点击事件的传递我在的android 中事件传递分析 已经学习过了,其中还涉及到view的绘制view绘制流程。
内容
点击某个button时,首先时ViewGroup接收到这个事件然后分发下去dispatchTouchEvent,最后到了你的button的(button继承自view)的onTouchEvent中
/**
* Implement this method to handle touch screen motion events.
*
* If this method is used to detect click actions, it is recommended that
* the actions be performed by implementing and calling
* {@link #performClick()}. This will ensure consistent system behavior,
* including:
*
*
obeying click sound preferences*
dispatching OnClickListener calls*
handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when* accessibility features are enabled
*
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
public boolean onTouchEvent(MotionEvent event) {
final int viewFlags = mViewFlags;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
// final int action = event.getAction();
// if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
// if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// setPressed(false);
// } else if ((mPrivateFlags & PFLAG_PREPRESSED) != 0) {
// removeTapCallback();
// }
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true);
}
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click action