做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. case MotionEvent.ACTION_DOWN:
  16. mHasPerformedLongPress = false;
  17. ......
  18. // Walk up the hierarchy to determine if we're inside a scrolling container.
  19. boolean isInScrollingContainer = isInScrollingContainer();//A已经是顶层元素了,没有ScrollView之类的控件存在,所以,isInScrollingContainer = false
  20. // For views inside a scrolling container, delay the pressed feedback for
  21. // a short period in case this is a scroll.
  22. if (isInScrollingContainer) {
  23. mPrivateFlags |= PFLAG_PREPRESSED;
  24. if (mPendingCheckForTap == null) {
  25. mPendingCheckForTap = new CheckForTap();
  26. }
  27. postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
  28. } else {
  29. // Not inside a scrolling container, so show the feedback right away
  30. setPressed(true);//A设置pressed = true
  31. checkForLongClick(0);
  32. }
  33. break;
  34. case MotionEvent.ACTION_CANCEL:
  35. ......
  36. break;
  37. case MotionEvent.ACTION_MOVE:
  38. ......
  39. break;
  40. }
  41. return true;
  42. }
  43. return false;
  44. }

从上面的代码我们知道,当手指触摸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. if (pressed) {
  12. mPrivateFlags |= PFLAG_PRESSED;
  13. } else {
  14. mPrivateFlags &= ~PFLAG_PRESSED;
  15. }
  16. if (needsRefresh) {
  17. refreshDrawableState();//切换背景图片
  18. }
  19. dispatchSetPressed(pressed);
  20. }

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. }

从上面的代码,可以看到,当设置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. case MotionEvent.ACTION_MOVE: {
  10. ......
  11. break;
  12. }
  13. case MotionEvent.ACTION_UP: {
  14. switch (mTouchMode) {
  15. case TOUCH_MODE_DOWN:
  16. case TOUCH_MODE_TAP:
  17. case TOUCH_MODE_DONE_WAITING:
  18. final int motionPosition = mMotionPosition;
  19. final View child = getChildAt(motionPosition - mFirstPosition);
  20. final float x = ev.getX();
  21. final boolean inList = x > mListPadding.left && x < getWidth() - mListPadding.right;
  22. if (child != null && !child.hasFocusable() && inList) {
  23. if (mTouchMode != TOUCH_MODE_DOWN) {
  24. child.setPressed(false);
  25. }
  26. if (mPerformClick == null) {
  27. mPerformClick = new PerformClick();
  28. }
  29. ......
  30. performClick.run();
  31. ......
  32. }
  33. ......
  34. case TOUCH_MODE_SCROLL:
  35. ......
  36. break;
  37. case TOUCH_MODE_OVERSCROLL:
  38. ......
  39. break;
  40. }
  41. ......
  42. case MotionEvent.ACTION_CANCEL: {
  43. ......
  44. break;
  45. }
  46. case MotionEvent.ACTION_POINTER_UP: {
  47. ......
  48. break;
  49. }
  50. case MotionEvent.ACTION_POINTER_DOWN: {
  51. ......
  52. break;
  53. }
  54. }
  55. return true;
  56. }

仅在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. if (isFocusable()) {
  10. return true;
  11. }
  12. final int descendantFocusability = getDescendantFocusability();
  13. if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
  14. final int count = mChildrenCount;
  15. final View[] children = mChildren;
  16. for (int i = 0; i < count; i++) {
  17. final View child = children[i];
  18. if (child.hasFocusable()) {
  19. return true;
  20. }
  21. }
  22. }
  23. return false;
  24. }

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

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

而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. if (dispatchItemClick) {
  7. handled |= super.performItemClick(view, position, id);
  8. }
  9. return handled;
  10. }

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. return false;
  20. }

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

设置特定的控件focusable = false

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

Pressed状态和clickable,duplicateParentState的关系的更多相关文章

  1. 点击ViewGroup时其子控件也变成pressed状态的原因分析及解决办法

    这个问题,当初在分析touch事件处理的时候按理应该分析到的,可是由于我当时觉得这块代码和touch的主题不是那么紧密, 就这么忽略掉了,直到后来在这上面遇到了问题.其实这个现象做Android开发的 ...

  2. 【Java EE 学习 45】【Hibernate学习第二天】【对象的三种状态】【一对多关系的操作】

    一.对象的三种状态. 1.对象有三种状态:持久化状态.临时状态.脱管状态(游离状态) 2.Session的特定方法能使得一个对象从一个状态转换到另外一个状态. 3.三种状态的说明 (1)临时状态:临时 ...

  3. Drawable(7)让一个没有pressed状态的控件使用StateList,显示pressed图片。

    TextView没有按下状态,Button有. 如图1,内容1在一个TextView上,默认它并没有按下状态. 如何让TextView有呢. 在xml中加入属性: android:clickable= ...

  4. hdu 1185 状压dp 好题 (当前状态与上两行有关系)

    /* 状压dp 刚开始&写成&&看了好长时间T0T. 状态转移方程 dp[i][k][j]=Max(dp[i][k][j],dp[i-1][l][k]+num[i][j]);( ...

  5. tcp 三次握手和四次断连深入分析:连接状态和socket API的关系----BAT 李运华

    http://blog.csdn.net/yunhua_lee/article/details/40513677 http://blog.csdn.net/yah99_wolf/article/cat ...

  6. http协议和web应用有状态和无状态浅析

    http协议和web应用有状态和无状态浅析 (2013-10-14 10:38:06) 转载▼ 标签: it   我们通常说的web应用程序的无状态性的含义是什么呢? 直观的说,“每次的请求都是独立的 ...

  7. (二十一)状态模式详解(DOTA版)

    作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 本次LZ给各位介绍状态模式, ...

  8. 用Asroute解决复杂状态切换问题

    项目地址:https://github.com/boycy815/asroute 首先明确几个概念 状态: 很多情况下,一个复杂的UI组件可能会有很多种不同的“状态”,不同的“状态”下组件本身对外界会 ...

  9. 24种设计模式--状态模式【State Pattern】

    现在城市发展很快,百万级人口的城市一堆一堆的,那其中有两个东西的发明在城市的发展中起到非常重要的作用:一个是汽车,一个呢是...,猜猜看,是什么?是电梯!汽车让城市可以横向扩展,电梯让城市可以纵向延伸 ...

随机推荐

  1. 【Foreign】无聊的计算姬 [Lucas][BSGS]

    无聊的计算姬 Time Limit: 10 Sec  Memory Limit: 256 MB Description Input Output Sample Input 6 2 2 3 4 3 2 ...

  2. Vijos 1232 核电站问题

    核电站问题 描述 一个核电站有N个放核物质的坑,坑排列在一条直线上.如果连续M个坑中放入核物质,则会发生爆炸,于是,在某些坑中可能不放核物质. 现在,请你计算:对于给定的N和M,求不发生爆炸的放置核物 ...

  3. MongoDB安装成为Windows服务

    使用以下命令将MongoDB安装成为Windows服务.笔者的MongoDB目录为C:\Program Files\MongoDB\Server\3.6\bin 切换到C:\Program Files ...

  4. Pycharm2017汉化包下载链接

    https://github.com/ewen0930/PyCharm-Chinese/tree/f5a8dc4a8f34398e81a69c69bb046aa4eff27c90 1.首先下载PyCh ...

  5. bayer转dng实现过程记录

    前言 项目中需要将imx185出来的raw数据转成dng格式,一开始认为很简单的事情,后面才发现还是挺复杂的!!!首先考虑的是不写任何代码,直接用adobe提供的转换工具来转,结果发现,不仅是adob ...

  6. PHPstorm创建注释模版

    /** * $NAME$ * @param * @return * @since $DATE$ * @author Name */$END$ /** * xxxx -­- Controller – 类 ...

  7. 动态加载ajax 腾讯视频评论

    import urllib import urllib2 import os import requests import re import json sns_url = 'http://sns.v ...

  8. docker从零开始(一)centos获取安装docker-ce

    卸载旧版本 较旧版本的Docker被称为docker或docker-engine.如果已安装这些,请卸载它们以及相关的依赖项. centos7 yum安装的docker就是docker-engine ...

  9. Vim常见配置与命令

    本文引自http://www.acczy.net/?p=301,在自己这里放一个以后方便查看 1. 基本安装 安装Vim,Windows系统中的主目录(类似于Linux的Home)中建立vimfile ...

  10. Android Studio查看类中所有方法和属性

    ctrl+f3效果: alt+7效果: 注意区别:虽然所有方法都有,但是顺序自己一看效果便知.一个是根据类中的顺序,另一个是根据a-z的开头字母顺序. 百度查了一下快捷键是ctrl+f12.但是自己试 ...