做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)。
從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);
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_MOVE:
}
return true;
}
return false;
}
從上面的代碼我們知道,當手指觸摸A的時候,A的pressed被設定為true。
接着,我們看看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,那又該如何修改?
那麼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未重載onTouchEvent事件,是以,需要看其父類的AbsListView.onTouchEvent(frameworks/base/core/java/android/widget/AbsListView):
public boolean onTouchEvent(MotionEvent ev) {
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
......
break;
case MotionEvent.ACTION_MOVE: {
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:
case MotionEvent.ACTION_CANCEL: {
case MotionEvent.ACTION_POINTER_UP: {
case MotionEvent.ACTION_POINTER_DOWN: {
return true;
僅在child.hasFocusable()=false時, PerformClick對象才會執行ViewGroup.hasFocusable:
* {@inheritDoc}
public boolean hasFocusable() {
if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
return false;
if (isFocusable()) {
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;
僅在所有的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):
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);
是以,如果ListView item中包含focusable為true的控件(例如:button, radiobutton),會導緻ItemClickListener失效。解決方案兩個:
設定特定的控件focusable = false
不使用onItemClickListener,而直接在Item上設定onClickListener監聽點選事件。
本文轉自 一點點征服 部落格園部落格,原文連結:http://www.cnblogs.com/ldq2016/p/8328107.html,如需轉載請自行聯系原作者