The status of the Android View and the re-drawing process analysis give you a step-by-step insight into the View (3)

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/17045157

In the previous article, I analyzed the view rendering process from the source code layer, I have learned how the onMeasure, onLayout, and onDraw steps work in the View Drawing Process. Today we will continue to explore the View in depth, learn about view status and redrawing. If you have not read the previous article, read it first.

I believe that when you use a View, you will find that it is stateful. For example, there is a button, which is an effect in a normal state, however, when the finger is pressed, it will become another effect, which will give people a feeling of clicking the button. Of course, this effect is believed to be implemented by almost all Android programmers, but since we have a deep understanding of the View, we should naturally know what the implementation principle behind it should be, let's explore it today.

I. View status

There are many types of view States. There are a total of more than a dozen types. However, in most cases, we only use several of them. Therefore, we only analyze the most commonly used view states.

1. enabled

Indicates whether the current view is available. You can call the setEnable () method to change the available status of the view. Pass true to indicate that the view is available, and pass false to indicate that the view is unavailable. The biggest difference between them is that unavailable views cannot respond to onTouch events.

2. focused

Indicates whether the current view gets the focus. Usually there are two ways to get the focus of the view, that is, to switch the view through the upper, lower, left, and right keys on the keyboard, and to call the requestFocus () method. Currently, almost no keyboard is available for Android phones. Therefore, you can use requestFocus () to focus the view. The requestFocus () method cannot guarantee that the view can obtain the focus. It has a Boolean return value. If true is returned, the focus is obtained successfully. If false is returned, the focus fails to be obtained. Generally, only when the focusable and focusable in touch mode of a view are both set up can the focus be obtained successfully, for example, EditText.

3. window_focused

Indicates whether the current view is in an interactive window. The value is automatically determined by the system, and the application cannot be changed.

4. selected

Indicates whether the current view is selected. Multiple Views can be selected in one interface. Calling the setSelected () method can change the selected view status. Passing true to select the view indicates that the view is selected, and passing false to indicate that the view is not selected.

5. pressed

Indicates whether the current view is in the pressed state. You can call the setPressed () method to change the status. If the parameter is set to true, the press is performed, and if the parameter is set to false, the press is not performed. In general, this status is automatically assigned by the system, but developers can also change it by calling this method.

We can create a selector file under the drawable directory of the project, and configure the background image corresponding to the view in each State. For example, to create a compose_bg.xml file, write the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/compose_pressed" android:state_pressed="true"></item>    <item android:drawable="@drawable/compose_pressed" android:state_focused="true"></item>    <item android:drawable="@drawable/compose_normal"></item></selector>
This Code indicates that the compose_normal background image is displayed when the view is in the normal state, and the compose_pressed background image is displayed when the view gets the focus or is pressed.

After the selector file is created, we can use it in the layout or code, for example, setting it as the background image of a button, as shown below:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button     android:id="@+id/compose"    android:layout_width="60dp"    android:layout_height="40dp"    android:layout_gravity="center_horizontal"    android:background="@drawable/compose_bg"    />    </LinearLayout>
Now run the program. This button will display different background images in normal and pressed states, as shown in:


protected void drawableStateChanged() {    Drawable d = mBGDrawable;    if (d != null && d.isStateful()) {        d.setState(getDrawableState());    }}
The first step here is to assign mBGDrawable to a Drawable object. What is this mBGDrawable? Observe the code in the setBackgroundResource () method, as shown below:
public void setBackgroundResource(int resid) {    if (resid != 0 && resid == mBackgroundResource) {        return;    }    Drawable d= null;    if (resid != 0) {        d = mResources.getDrawable(resid);    }    setBackgroundDrawable(d);    mBackgroundResource = resid;}
You can see that in row 7th, The getDrawable () method of Resource is called to convert resid into a Drawable object, and then the setBackgroundDrawable () method is called and the Drawable object is passed in. In setBackgroundDrawable () the passed Drawable object is assigned to mBGDrawable.

public final int[] getDrawableState() {    if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {        return mDrawableState;    } else {        mDrawableState = onCreateDrawableState(0);        mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;        return mDrawableState;    }}
Here, we will first determine whether the current view status has changed. If it has not changed, we will directly return the current view status. If it has changed, we will call onCreateDrawableState () method to obtain the latest view status. All views are returned in an integer array.

public boolean setState(final int[] stateSet) {    if (!Arrays.equals(mStateSet, stateSet)) {        mStateSet = stateSet;        return onStateChange(stateSet);    }    return false;}
Here, the Arrays. equals () method is called to determine whether the array of view status has changed. If yes, the onStateChange () method is called; otherwise, false is returned directly. However, you will find that the onStateChange () method of Drawable simply returns a false value without any logic processing. Why? This is mainly because the mBGDrawable object is created through a selector file, and the Drawable object created through this file is actually a StateListDrawable instance, so onStateChange () called here () the method actually calls the onStateChange () method in StateListDrawable, so let's take a look:
@Overrideprotected boolean onStateChange(int[] stateSet) {    int idx = mStateListState.indexOfStateSet(stateSet);    if (DEBUG) android.util.Log.i(TAG, "onStateChange " + this + " states "            + Arrays.toString(stateSet) + " found " + idx);    if (idx < 0) {        idx = mStateListState.indexOfStateSet(StateSet.WILD_CARD);    }    if (selectDrawable(idx)) {        return true;    }    return super.onStateChange(stateSet);}

As you can see, the indexOfStateSet () method is called to find the Drawable resource subscript corresponding to the current view status.

Although the view is automatically drawn to the screen after the Activity is loaded, we have a reason to dynamically update the view when interacting with the Activity, for example, changing the view status and displaying or hiding a widget. At this time, the previously drawn view has actually expired. At this time, we should re-paint the view.

When you call methods such as setVisibility (), setEnabled (), and setSelected () of a view, the view is repainted. If you want to manually force the view to be repainted, you can call the invalidate () method. Of course, setVisibility (), setEnabled (), setSelected () and other methods are actually implemented by calling the invalidate () method, so let's take a look at invalidate () what is the method code.

The View Source Code contains several invalidate () methods and one invalidateDrawable () method. Of course, their principles are the same. Therefore, we only analyze one of them. The Code is as follows:

void invalidate(boolean invalidateCache) {    if (ViewDebug.TRACE_HIERARCHY) {        ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);    }    if (skipInvalidate()) {        return;    }    if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||            (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||            (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {        mLastIsOpaque = isOpaque();        mPrivateFlags &= ~DRAWN;        mPrivateFlags |= DIRTY;        if (invalidateCache) {            mPrivateFlags |= INVALIDATED;            mPrivateFlags &= ~DRAWING_CACHE_VALID;        }        final AttachInfo ai = mAttachInfo;        final ViewParent p = mParent;        if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {            if (p != null && ai != null && ai.mHardwareAccelerated) {                p.invalidateChild(this, null);                return;            }        }        if (p != null && ai != null) {            final Rect r = ai.mTmpInvalRect;            r.set(0, 0, mRight - mLeft, mBottom - mTop);            p.invalidateChild(this, r);        }    }}
In this method, the skipInvalidate () method is called to determine whether the current View needs to be re-painted, and the judgment logic is relatively simple. If the View is invisible and no animation is executed, I think it does not need to be re-painted. Then, the system checks the transparency and adds some tag bits to the View, and then calls
public final void invalidateChild(View child, final Rect dirty) {    ViewParent parent = this;    final AttachInfo attachInfo = mAttachInfo;    if (attachInfo != null) {        final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;        if (dirty == null) {            ......        } else {            ......            do {                View view = null;                if (parent instanceof View) {                    view = (View) parent;                    if (view.mLayerType != LAYER_TYPE_NONE &&                            view.getParent() instanceof View) {                        final View grandParent = (View) view.getParent();                        grandParent.mPrivateFlags |= INVALIDATED;                        grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;                    }                }                if (drawAnimation) {                    if (view != null) {                        view.mPrivateFlags |= DRAW_ANIMATION;                    } else if (parent instanceof ViewRootImpl) {                        ((ViewRootImpl) parent).mIsAnimating = true;                    }                }                if (view != null) {                    if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&                            view.getSolidColor() == 0) {                        opaqueFlag = DIRTY;                    }                    if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) {                        view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;                    }                }                parent = parent.invalidateChildInParent(location, dirty);                if (view != null) {                    Matrix m = view.getMatrix();                    if (!m.isIdentity()) {                        RectF boundingRect = attachInfo.mTmpTransformRect;                        boundingRect.set(dirty);                        m.mapRect(boundingRect);                        dirty.set((int) boundingRect.left, (int) boundingRect.top,                                (int) (boundingRect.right + 0.5f),                                (int) (boundingRect.bottom + 0.5f));                    }                }            } while (parent != null);        }    }}
We can see that there is a while loop in row 10th. When ViewParent is not empty, it will keep repeating. In this while loop, the parent layout of the current layout is continuously obtained and its invalidateChildInParent () method is called.
    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {        invalidateChild(null, dirty);        return null;    }
The code here is very simple, just calling the invalidateChild () method. Let's take a look at it again:
public void invalidateChild(View child, Rect dirty) {    checkThread();    if (LOCAL_LOGV) Log.v(TAG, "Invalidate child: " + dirty);    mDirty.union(dirty);    if (!mWillDrawSoon) {        scheduleTraversals();    }}
This method is not long. It calls the scheduleTraversals () method in row 6th, so we will continue to follow up:
public void scheduleTraversals() {    if (!mTraversalScheduled) {        mTraversalScheduled = true;        sendEmptyMessage(DO_TRAVERSAL);    }}
We can see that the sendEmptyMessage () method is called and a DO_TRAVERSAL parameter is passed in. Anyone who knows about the Android asynchronous message processing mechanism will know that a Handler of a task can call the sendEmptyMessage () method to send messages and receive messages in the handleMessage () method, if you look at the ViewRoot class definition, you will find that it inherits from Handler, that is, the call
public void handleMessage(Message msg) {    switch (msg.what) {    case DO_TRAVERSAL:        if (mProfile) {            Debug.startMethodTracing("ViewRoot");        }        performTraversals();        if (mProfile) {            Debug.stopMethodTracing();            mProfile = false;        }        break;    ......}

The familiar code has appeared! Here, the objective mtraversals () method is called in Row 3. Isn't that the entry to view plotting we learned in the previous article? Although a lot of calls have been made, it is certain that the invalidate () method of the view will be called in this article.

public boolean selectDrawable(int idx) {    if (idx == mCurIndex) {        return false;    }    final long now = SystemClock.uptimeMillis();    if (mDrawableContainerState.mExitFadeDuration > 0) {        if (mLastDrawable != null) {            mLastDrawable.setVisible(false, false);        }        if (mCurrDrawable != null) {            mLastDrawable = mCurrDrawable;            mExitAnimationEnd = now + mDrawableContainerState.mExitFadeDuration;        } else {            mLastDrawable = null;            mExitAnimationEnd = 0;        }    } else if (mCurrDrawable != null) {        mCurrDrawable.setVisible(false, false);    }    if (idx >= 0 && idx < mDrawableContainerState.mNumChildren) {        Drawable d = mDrawableContainerState.mDrawables[idx];        mCurrDrawable = d;        mCurIndex = idx;        if (d != null) {            if (mDrawableContainerState.mEnterFadeDuration > 0) {                mEnterAnimationEnd = now + mDrawableContainerState.mEnterFadeDuration;            } else {                d.setAlpha(mAlpha);            }            d.setVisible(isVisible(), true);            d.setDither(mDrawableContainerState.mDither);            d.setColorFilter(mColorFilter);            d.setState(getState());            d.setLevel(getLevel());            d.setBounds(getBounds());        }    } else {        mCurrDrawable = null;        mCurIndex = -1;    }    if (mEnterAnimationEnd != 0 || mExitAnimationEnd != 0) {        if (mAnimationRunnable == null) {            mAnimationRunnable = new Runnable() {                @Override public void run() {                    animate(true);                    invalidateSelf();                }            };        } else {            unscheduleSelf(mAnimationRunnable);        }        animate(true);    }    invalidateSelf();    return true;}
We can skip the previous code here. The key is to see that the invalidateSelf () method will be called in line 54th. The code in this method is as follows:
public void invalidateSelf() {    final Callback callback = getCallback();    if (callback != null) {        callback.invalidateDrawable(this);    }}
We can see that the getCallback () method is called to obtain the Callback instance of the Callback interface, and then the invalidateDrawable () method of the Callback instance is called. So what is the callback instance here? Observe the class definition of View, as shown below:
public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,AccessibilityEventSource {    ......}
View class is implemented

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.