[关闭]
@act262 2017-06-03T11:38:22.000000Z 字数 1198 阅读 1186

StateListDrawable、selector执行顺序分析

Android_Drawable


在selector或者StateListDrawable的从上到下按顺序优先匹配

分析源码

StateListDrawable.java

  1. // 添加对应状态的Drawable时插入Container数组的最后
  2. public void addState(int[] stateSet, Drawable drawable) {
  3. if (drawable != null) {
  4. mStateListState.addStateSet(stateSet, drawable);
  5. // in case the new state matches our current state...
  6. onStateChange(getState());
  7. }
  8. }
  9. @Override
  10. // 主动或者被动触发调用
  11. protected boolean onStateChange(int[] stateSet) {
  12. final boolean changed = super.onStateChange(stateSet);
  13. int idx = mStateListState.indexOfStateSet(stateSet);
  14. // 都没有匹配到,则使用兜底方案
  15. if (idx < 0) {
  16. idx = mStateListState.indexOfStateSet(StateSet.WILD_CARD);
  17. }
  18. return selectDrawable(idx) || changed;
  19. }

StateListState

  1. // 获取指定状态的索引
  2. int indexOfStateSet(int[] stateSet) {
  3. final int[][] stateSets = mStateSets;
  4. final int N = getChildCount();
  5. for (int i = 0; i < N; i++) {
  6. if (StateSet.stateSetMatches(stateSets[i], stateSet)) {
  7. return i;
  8. }
  9. }
  10. return -1;
  11. }

StateSet.java

  1. /**
  2. * A state specification that will be matched by all StateSets.
  3. */
  4. public static final int[] WILD_CARD = new int[0];
  5. /**
  6. * A state set that does not contain any valid states.
  7. */
  8. public static final int[] NOTHING = new int[] { 0 };
  9. public static boolean stateSetMatches(int[] stateSpec, int[] stateSet) {
  10. // 这里优先匹配了
  11. if (stateSet == null) {
  12. return (stateSpec == null || isWildCard(stateSpec));
  13. }
  14. // 匹配指定的顺序,从上到下优先匹配
  15. // ...
  16. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注