Pressed状态和clickable,duplicateParentState的关系

    做Android开发的人都用过Selector,可以方便的实现View在不同状态下的背景。不过,相信大部分开发者遇到过和我一样的问题,本文会从源码角度,解释这些问题。


        首先,这里简单描述一下,我遇到的问题:

界面上有个全屏的LinearLayout A,A中有一个TextView B和Button C,其中,A的clickable=true,并设置了pressed时,背景色为灰色,B设置了pressed时,背景色为蓝色

当手指触摸C下方的空白区域时,看到了这样的效果:

        在这里看到,在没有触摸B的情况下,B的pressed = true,而C的pressed = false。 C的状态暂且不讨论,按照Android消息传递的原则,因为touch的point不在B内部,所以,touch消息应该不会交给B处理,那为什么B的pressed = true?

         下面开始一步一步分析(本文分析的Android源码为4.2.2)。

Pressed状态的设定

        从View.onTouchEvent函数看起(frameworks/base/core/java/android/view/View.java):

  1. /** 
  2.  * Implement this method to handle touch screen motion events. 
  3.  * 
  4.  * @param event The motion event. 
  5.  * @return True if the event was handled, false otherwise. 
  6.  */  
  7. public boolean onTouchEvent(MotionEvent event) {  
  8.     ......  
  9.     if (((viewFlags & CLICKABLE) == CLICKABLE || //这里是为什么设置A的clickable为true的原因,否则,press A的时候,没有界面元素处理touch event,最终会由Activity的onTouchEvent函数处理  
  10.             (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {  
  11.         switch (event.getAction()) {  
  12.             case MotionEvent.ACTION_UP:  
  13.                 ......  
  14.                 break;  
  15.   
  16.             case MotionEvent.ACTION_DOWN:  
  17.                 mHasPerformedLongPress = false;  
  18.                 ......  
  19.                 // Walk up the hierarchy to determine if we're inside a scrolling container.  
  20.                 boolean isInScrollingContainer = isInScrollingContainer();//A已经是顶层元素了,没有ScrollView之类的控件存在,所以,isInScrollingContainer = false  
  21.   
  22.                 // For views inside a scrolling container, delay the pressed feedback for  
  23.                 // a short period in case this is a scroll.  
  24.                 if (isInScrollingContainer) {  
  25.                     mPrivateFlags |= PFLAG_PREPRESSED;  
  26.                     if (mPendingCheckForTap == null) {  
  27.                         mPendingCheckForTap = new CheckForTap();  
  28.                     }  
  29.                     postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());  
  30.                 } else {  
  31.                     // Not inside a scrolling container, so show the feedback right away  
  32.                     setPressed(true);//A设置pressed = true  
  33.                     checkForLongClick(0);  
  34.                 }  
  35.                 break;  
  36.   
  37.             case MotionEvent.ACTION_CANCEL:  
  38.                 ......  
  39.                 break;  
  40.   
  41.             case MotionEvent.ACTION_MOVE:  
  42.                 ......  
  43.                 break;  
  44.         }  
  45.         return true;  
  46.     }  
  47.   
  48.     return false;  
  49. }  

       

        从上面的代码我们知道,当手指触摸A的时候,A的pressed被设置为true。

Pressed状态的传递

        接着,我们看看setPressed函数的实现:

  1. /** 
  2.  * Sets the pressed state for this view. 
  3.  * 
  4.  * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 
  5.  *                the View's internal state from a previously set "pressed" state. 
  6.  * @see #isClickable() 
  7.  * @see #setClickable(boolean) 
  8.  */  
  9. public void setPressed(boolean pressed) {  
  10.     final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);  
  11.   
  12.     if (pressed) {  
  13.         mPrivateFlags |= PFLAG_PRESSED;  
  14.     } else {  
  15.         mPrivateFlags &= ~PFLAG_PRESSED;  
  16.     }  
  17.   
  18.     if (needsRefresh) {  
  19.         refreshDrawableState();//切换背景图片  
  20.     }  
  21.     dispatchSetPressed(pressed);  
  22. }  

        setPressed函数内部调用了dispatchSetPressed函数,这个让人很在意(frameworks/base/core/java/android/view/ViewGroup.java):

  1. @Override  
  2. protected void dispatchSetPressed(boolean pressed) {  
  3.     final View[] children = mChildren;  
  4.     final int count = mChildrenCount;  
  5.     for (int i = 0; i < count; i++) {  
  6.         final View child = children[i];  
  7.         // Children that are clickable on their own should not  
  8.         // show a pressed state when their parent view does.  
  9.         // Clearing a pressed state always propagates.  
  10.         if (!pressed || (!child.isClickable() && !child.isLongClickable())) {  
  11.             child.setPressed(pressed);  
  12.         }  
  13.     }  
  14. }  

        原来,dispatchSetPressed函数会把pressed状态传递给所有clickable=false并且longclickable=false的子元素。

        到这里,前面的现象就可以解释了,因为C是button类,clickable=true,而B的clickable=false。所以,当A被触摸时,B的pressed=true,而C的pressed=false。那么,可以回答下面几个小问题了:

  1. 如果不希望A的pressed=true时,B的pressed = true,该如何修改?
    1. 设置B的clickable=true
  2. 如果希望A的pressed = true时,C的pressed = true,那又该如何修改?
    1. 设置C的clickable = false. 但是,这里可能又存在问题了,设置C的clickable=false,会导致button按钮的onclicklistener无法工作,这是个严重的副作用。那么可以不修改clickable,而设置android:duplicateParentState为true。

       那么duplicateParentState做了些什么呢?View.setDuplicateParentStateEnabled:

  1. public void setDuplicateParentStateEnabled(boolean enabled) {  
  2.     setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);  
  3. }  

      再看看View.onCreateDrawableState()

  1. /** 
  2.     * Generate the new {@link android.graphics.drawable.Drawable} state for 
  3.     * this view. This is called by the view 
  4.     * system when the cached Drawable state is determined to be invalid.  To 
  5.     * retrieve the current state, you should use {@link #getDrawableState}. 
  6.     * 
  7.     * @param extraSpace if non-zero, this is the number of extra entries you 
  8.     *                   would like in the returned array in which you can place your own 
  9.     *                   states. 
  10.     * @return Returns an array holding the current {@link Drawable} state of 
  11.     * the view. 
  12.     * @see #mergeDrawableStates(int[], int[]) 
  13.     */  
  14.    protected int[] onCreateDrawableState(int extraSpace) {  
  15.        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&  
  16.                mParent instanceof View) {  
  17.            return ((View) mParent).onCreateDrawableState(extraSpace);  
  18.        }  
  19.   
  20.        ......  
  21.    }  

        从上面的代码,可以看到,当设置duplicateParentState为true时,View的DrawableState直接使用了其parent的。所以,他的drawable状态会一直保持与其parent同步。

题外,为什么当ListView中包含focusable为true的控件时,OnItemClickListener不会触发

        因为ListView未重载onTouchEvent事件,所以,需要看其父类的AbsListView.onTouchEvent(frameworks/base/core/java/android/widget/AbsListView):

  1. @Override  
  2. public boolean onTouchEvent(MotionEvent ev) {  
  3.     ......  
  4.     switch (action & MotionEvent.ACTION_MASK) {  
  5.     case MotionEvent.ACTION_DOWN: {  
  6.         ......  
  7.         break;  
  8.     }  
  9.   
  10.     case MotionEvent.ACTION_MOVE: {  
  11.         ......  
  12.         break;  
  13.     }  
  14.   
  15.     case MotionEvent.ACTION_UP: {  
  16.         switch (mTouchMode) {  
  17.         case TOUCH_MODE_DOWN:  
  18.         case TOUCH_MODE_TAP:  
  19.         case TOUCH_MODE_DONE_WAITING:  
  20.             final int motionPosition = mMotionPosition;  
  21.             final View child = getChildAt(motionPosition - mFirstPosition);  
  22.   
  23.             final float x = ev.getX();  
  24.             final boolean inList = x > mListPadding.left && x < getWidth() - mListPadding.right;  
  25.   
  26.             if (child != null && !child.hasFocusable() && inList) {  
  27.                 if (mTouchMode != TOUCH_MODE_DOWN) {  
  28.                     child.setPressed(false);  
  29.                 }  
  30.   
  31.                 if (mPerformClick == null) {  
  32.                     mPerformClick = new PerformClick();  
  33.                 }  
  34.   
  35.                 ......  
  36.                 performClick.run();  
  37.                 ......  
  38.             }  
  39.             ......  
  40.         case TOUCH_MODE_SCROLL:  
  41.             ......  
  42.             break;  
  43.   
  44.         case TOUCH_MODE_OVERSCROLL:  
  45.         ......  
  46.         break;  
  47.     }  
  48.     ......  
  49.     case MotionEvent.ACTION_CANCEL: {  
  50.         ......  
  51.         break;  
  52.     }  
  53.   
  54.     case MotionEvent.ACTION_POINTER_UP: {  
  55.         ......  
  56.         break;  
  57.     }  
  58.   
  59.     case MotionEvent.ACTION_POINTER_DOWN: {  
  60.         ......  
  61.         break;  
  62.     }  
  63.     }  
  64.   
  65.     return true;  
  66. }  

         仅在child.hasFocusable()=false时, PerformClick对象才会执行ViewGroup.hasFocusable:

  1. /** 
  2.  * {@inheritDoc} 
  3.  */  
  4. @Override  
  5. public boolean hasFocusable() {  
  6.     if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {  
  7.         return false;  
  8.     }  
  9.   
  10.     if (isFocusable()) {  
  11.         return true;  
  12.     }  
  13.   
  14.     final int descendantFocusability = getDescendantFocusability();  
  15.     if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {  
  16.         final int count = mChildrenCount;  
  17.         final View[] children = mChildren;  
  18.   
  19.         for (int i = 0; i < count; i++) {  
  20.             final View child = children[i];  
  21.             if (child.hasFocusable()) {  
  22.                 return true;  
  23.             }  
  24.         }  
  25.     }  
  26.   
  27.     return false;  
  28. }  

        仅在所有的clild的hasFocusable为false时,ListView才会执行performClick(AbsListView.PerformClick):

  1. private class PerformClick extends WindowRunnnable implements Runnable {  
  2.     int mClickMotionPosition;  
  3.   
  4.     public void run() {  
  5.         // The data has changed since we posted this action in the event queue,  
  6.         // bail out before bad things happen  
  7.         if (mDataChanged) return;  
  8.   
  9.         final ListAdapter adapter = mAdapter;  
  10.         final int motionPosition = mClickMotionPosition;  
  11.         if (adapter != null && mItemCount > 0 &&  
  12.                 motionPosition != INVALID_POSITION &&  
  13.                 motionPosition < adapter.getCount() && sameWindow()) {  
  14.             final View view = getChildAt(motionPosition - mFirstPosition);  
  15.             // If there is no view, something bad happened (the view scrolled off the  
  16.             // screen, etc.) and we should cancel the click  
  17.             if (view != null) {  
  18.                 performItemClick(view, motionPosition, adapter.getItemId(motionPosition));  
  19.             }  
  20.         }  
  21.     }  
  22. }  

        而PerformClick会调用performItemClick(AdsListView.performItemClick):

  1. @Override  
  2.    public boolean performItemClick(View view, int position, long id) {  
  3.        boolean handled = false;  
  4.        boolean dispatchItemClick = true;  
  5.   
  6.        ......  
  7.   
  8.        if (dispatchItemClick) {  
  9.            handled |= super.performItemClick(view, position, id);  
  10.        }  
  11.   
  12.        return handled;  
  13.    }  

       AdapterView.preformItemClick:

  1. /** 
  2.  * Call the OnItemClickListener, if it is defined. 
  3.  * 
  4.  * @param view The view within the AdapterView that was clicked. 
  5.  * @param position The position of the view in the adapter. 
  6.  * @param id The row id of the item that was clicked. 
  7.  * @return True if there was an assigned OnItemClickListener that was 
  8.  *         called, false otherwise is returned. 
  9.  */  
  10. public boolean performItemClick(View view, int position, long id) {  
  11.     if (mOnItemClickListener != null) {  
  12.         playSoundEffect(SoundEffectConstants.CLICK);  
  13.         if (view != null) {  
  14.             view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);  
  15.         }  
  16.         mOnItemClickListener.onItemClick(this, view, position, id);  
  17.         return true;  
  18.     }  
  19.   
  20.     return false;  
  21. }  


        所以,如果ListView item中包含focusable为true的控件(例如:button, radiobutton),会导致ItemClickListener失效。解决方案两个:

设置特定的控件focusable = false

不使用onItemClickListener,而直接在Item上设置onClickListener监听点击事件。

原文地址:https://www.cnblogs.com/ldq2016/p/8328107.html