做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):
- /**
- * Implement this method to handle touch screen motion events.
- *
- * @param event The motion event.
- * @return True if the event was handled, false otherwise.
- */
- public boolean onTouchEvent(MotionEvent event) {
- ......
- if (((viewFlags & CLICKABLE) == CLICKABLE || //这里是为什么设置A的clickable为true的原因,否则,press A的时候,没有界面元素处理touch event,最终会由Activity的onTouchEvent函数处理
- (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_UP:
- ......
- break;
- case MotionEvent.ACTION_DOWN:
- mHasPerformedLongPress = false;
- ......
- // Walk up the hierarchy to determine if we're inside a scrolling container.
- boolean isInScrollingContainer = isInScrollingContainer();//A已经是顶层元素了,没有ScrollView之类的控件存在,所以,isInScrollingContainer = false
- // For views inside a scrolling container, delay the pressed feedback for
- // a short period in case this is a scroll.
- if (isInScrollingContainer) {
- mPrivateFlags |= PFLAG_PREPRESSED;
- if (mPendingCheckForTap == null) {
- mPendingCheckForTap = new CheckForTap();
- }
- postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
- } else {
- // Not inside a scrolling container, so show the feedback right away
- setPressed(true);//A设置pressed = true
- checkForLongClick(0);
- }
- break;
- case MotionEvent.ACTION_CANCEL:
- ......
- break;
- case MotionEvent.ACTION_MOVE:
- ......
- break;
- }
- return true;
- }
- return false;
- }
从上面的代码我们知道,当手指触摸A的时候,A的pressed被设置为true。
Pressed状态的传递
接着,我们看看setPressed函数的实现:
- /**
- * Sets the pressed state for this view.
- *
- * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
- * the View's internal state from a previously set "pressed" state.
- * @see #isClickable()
- * @see #setClickable(boolean)
- */
- public void setPressed(boolean pressed) {
- final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
- if (pressed) {
- mPrivateFlags |= PFLAG_PRESSED;
- } else {
- mPrivateFlags &= ~PFLAG_PRESSED;
- }
- if (needsRefresh) {
- refreshDrawableState();//切换背景图片
- }
- dispatchSetPressed(pressed);
- }
setPressed函数内部调用了dispatchSetPressed函数,这个让人很在意(frameworks/base/core/java/android/view/ViewGroup.java):
- @Override
- protected void dispatchSetPressed(boolean pressed) {
- final View[] children = mChildren;
- final int count = mChildrenCount;
- for (int i = 0; i < count; i++) {
- final View child = children[i];
- // Children that are clickable on their own should not
- // show a pressed state when their parent view does.
- // Clearing a pressed state always propagates.
- if (!pressed || (!child.isClickable() && !child.isLongClickable())) {
- child.setPressed(pressed);
- }
- }
- }
原来,dispatchSetPressed函数会把pressed状态传递给所有clickable=false并且longclickable=false的子元素。
到这里,前面的现象就可以解释了,因为C是button类,clickable=true,而B的clickable=false。所以,当A被触摸时,B的pressed=true,而C的pressed=false。那么,可以回答下面几个小问题了:
- 如果不希望A的pressed=true时,B的pressed = true,该如何修改?
- 设置B的clickable=true
- 如果希望A的pressed = true时,C的pressed = true,那又该如何修改?
- 设置C的clickable = false. 但是,这里可能又存在问题了,设置C的clickable=false,会导致button按钮的onclicklistener无法工作,这是个严重的副作用。那么可以不修改clickable,而设置为true。
那么duplicateParentState做了些什么呢?View.setDuplicateParentStateEnabled:
- public void setDuplicateParentStateEnabled(boolean enabled) {
- setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
- }
再看看View.onCreateDrawableState()
- /**
- * Generate the new {@link android.graphics.drawable.Drawable} state for
- * this view. This is called by the view
- * system when the cached Drawable state is determined to be invalid. To
- * retrieve the current state, you should use {@link #getDrawableState}.
- *
- * @param extraSpace if non-zero, this is the number of extra entries you
- * would like in the returned array in which you can place your own
- * states.
- * @return Returns an array holding the current {@link Drawable} state of
- * the view.
- * @see #mergeDrawableStates(int[], int[])
- */
- protected int[] onCreateDrawableState(int extraSpace) {
- if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
- mParent instanceof View) {
- return ((View) mParent).onCreateDrawableState(extraSpace);
- }
- ......
- }
从上面的代码,可以看到,当设置duplicateParentState为true时,View的DrawableState直接使用了其parent的。所以,他的drawable状态会一直保持与其parent同步。
题外,为什么当ListView中包含focusable为true的控件时,OnItemClickListener不会触发
因为ListView未重载onTouchEvent事件,所以,需要看其父类的AbsListView.onTouchEvent(frameworks/base/core/java/android/widget/AbsListView):
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- ......
- switch (action & MotionEvent.ACTION_MASK) {
- case MotionEvent.ACTION_DOWN: {
- ......
- break;
- }
- case MotionEvent.ACTION_MOVE: {
- ......
- break;
- }
- case MotionEvent.ACTION_UP: {
- switch (mTouchMode) {
- case TOUCH_MODE_DOWN:
- case TOUCH_MODE_TAP:
- case TOUCH_MODE_DONE_WAITING:
- final int motionPosition = mMotionPosition;
- final View child = getChildAt(motionPosition - mFirstPosition);
- final float x = ev.getX();
- final boolean inList = x > mListPadding.left && x < getWidth() - mListPadding.right;
- if (child != null && !child.hasFocusable() && inList) {
- if (mTouchMode != TOUCH_MODE_DOWN) {
- child.setPressed(false);
- }
- if (mPerformClick == null) {
- mPerformClick = new PerformClick();
- }
- ......
- performClick.run();
- ......
- }
- ......
- case TOUCH_MODE_SCROLL:
- ......
- break;
- case TOUCH_MODE_OVERSCROLL:
- ......
- break;
- }
- ......
- case MotionEvent.ACTION_CANCEL: {
- ......
- break;
- }
- case MotionEvent.ACTION_POINTER_UP: {
- ......
- break;
- }
- case MotionEvent.ACTION_POINTER_DOWN: {
- ......
- break;
- }
- }
- return true;
- }
仅在child.hasFocusable()=false时, PerformClick对象才会执行ViewGroup.hasFocusable:
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean hasFocusable() {
- if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
- return false;
- }
- if (isFocusable()) {
- return true;
- }
- final int descendantFocusability = getDescendantFocusability();
- if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
- final int count = mChildrenCount;
- final View[] children = mChildren;
- for (int i = 0; i < count; i++) {
- final View child = children[i];
- if (child.hasFocusable()) {
- return true;
- }
- }
- }
- return false;
- }
仅在所有的clild的hasFocusable为false时,ListView才会执行performClick(AbsListView.PerformClick):
- private class PerformClick extends WindowRunnnable implements Runnable {
- int mClickMotionPosition;
- public void run() {
- // The data has changed since we posted this action in the event queue,
- // bail out before bad things happen
- if (mDataChanged) return;
- final ListAdapter adapter = mAdapter;
- final int motionPosition = mClickMotionPosition;
- if (adapter != null && mItemCount > 0 &&
- motionPosition != INVALID_POSITION &&
- motionPosition < adapter.getCount() && sameWindow()) {
- final View view = getChildAt(motionPosition - mFirstPosition);
- // If there is no view, something bad happened (the view scrolled off the
- // screen, etc.) and we should cancel the click
- if (view != null) {
- performItemClick(view, motionPosition, adapter.getItemId(motionPosition));
- }
- }
- }
- }
而PerformClick会调用performItemClick(AdsListView.performItemClick):
- @Override
- public boolean performItemClick(View view, int position, long id) {
- boolean handled = false;
- boolean dispatchItemClick = true;
- ......
- if (dispatchItemClick) {
- handled |= super.performItemClick(view, position, id);
- }
- return handled;
- }
AdapterView.preformItemClick:
- /**
- * Call the OnItemClickListener, if it is defined.
- *
- * @param view The view within the AdapterView that was clicked.
- * @param position The position of the view in the adapter.
- * @param id The row id of the item that was clicked.
- * @return True if there was an assigned OnItemClickListener that was
- * called, false otherwise is returned.
- */
- public boolean performItemClick(View view, int position, long id) {
- if (mOnItemClickListener != null) {
- playSoundEffect(SoundEffectConstants.CLICK);
- if (view != null) {
- view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
- }
- mOnItemClickListener.onItemClick(this, view, position, id);
- return true;
- }
- return false;
- }
所以,如果ListView item中包含focusable为true的控件(例如:button, radiobutton),会导致ItemClickListener失效。解决方案两个:
设置特定的控件focusable = false
不使用onItemClickListener,而直接在Item上设置onClickListener监听点击事件。