android自訂控制項系列教程----視圖
理解android視圖對於android裝置我們所看到的地區其實和它在底層的繪製有著很大的關係,很多時候我們都只關心我們所看到的,那麼在底層一點它到底是怎麼樣的一個東西呢?讓我們先來看看這個圖。
對於整個裝置的可見地區而言其實就是我們中間的那個螢幕,從上面的拿個圖可以清晰的看到,除了我們的可見地區在它的上下左右都應該有內容,那麼在android系統中是怎麼控制顯示它的位置呢?下面我們來解答這個問題。android如何控制視圖的顯示位置我們可以開啟view類的源碼找到這兩個函數
/** * Set the scrolled position of your view. This will cause a call to * {@link #onScrollChanged(int, int, int, int)} and the view will be * invalidated. * @param x the x position to scroll to * @param y the y position to scroll to */ public void scrollTo(int x, int y) { if (mScrollX != x || mScrollY != y) { int oldX = mScrollX; int oldY = mScrollY; mScrollX = x; mScrollY = y; invalidateParentCaches(); onScrollChanged(mScrollX, mScrollY, oldX, oldY); if (!awakenScrollBars()) { postInvalidateOnAnimation(); } } }還有一個是
/** * Move the scrolled position of your view. This will cause a call to * {@link #onScrollChanged(int, int, int, int)} and the view will be * invalidated. * @param x the amount of pixels to scroll by horizontally * @param y the amount of pixels to scroll by vertically */ public void scrollBy(int x, int y) { scrollTo(mScrollX + x, mScrollY + y); }我們仔細的來解讀一下上面的函數。這個源碼我是摘自5.0的源碼。我們看到ScrollBy這個函數也是調用的ScrollTo我們就來分析一下ScrollTo這個函數到底做了什麼工作?很簡單的幾句代碼,最重要的一句就是這一句 postInvalidateOnAnimation();這一句代碼會去回調我們的ondraw函數,在ondraw函數裡面繪製我們的可見地區,然後我們在來看看VIew的draw的方法
* Manually render this view (and all of its children) to the given Canvas. * The view must have already done a full layout before this function is * called. When implementing a view, implement * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. * If you do need to override this method, call the superclass version. * * @param canvas The Canvas to which the View is rendered. */ public void draw(Canvas canvas) { if (mClipBounds != null) { canvas.clipRect(mClipBounds); } final int privateFlags = mPrivateFlags; final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; /* * Draw traversal performs several drawing steps which must be executed * in the appropriate order: * * 1. Draw the background * 2. If necessary, save the canvas' layers to prepare for fading * 3. Draw view's content * 4. Draw children * 5. If necessary, draw the fading edges and restore layers * 6. Draw decorations (scrollbars for instance) */ // Step 1, draw the background, if needed int saveCount; if (!dirtyOpaque) { final Drawable background = mBackground; if (background != null) { final int scrollX = mScrollX; final int scrollY = mScrollY; if (mBackgroundSizeChanged) { background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); mBackgroundSizeChanged = false; } if ((scrollX | scrollY) == 0) { background.draw(canvas); } else { canvas.translate(scrollX, scrollY); background.draw(canvas); canvas.translate(-scrollX, -scrollY); } } } // skip step 2 & 5 if possible (common case) final int viewFlags = mViewFlags; boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; if (!verticalEdges && !horizontalEdges) { // Step 3, draw the content if (!dirtyOpaque) onDraw(canvas); // Step 4, draw the children dispatchDraw(canvas); // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); if (mOverlay != null && !mOverlay.isEmpty()) { mOverlay.getOverlayView().dispatchDraw(canvas); } // we're done... return; } /* * Here we do the full fledged routine... * (this is an uncommon case where speed matters less, * this is why we repeat some of the tests that have been * done above) */ boolean drawTop = false; boolean drawBottom = false; boolean drawLeft = false; boolean drawRight = false; float topFadeStrength = 0.0f; float bottomFadeStrength = 0.0f; float leftFadeStrength = 0.0f; float rightFadeStrength = 0.0f; // Step 2, save the canvas' layers int paddingLeft = mPaddingLeft; final boolean offsetRequired = isPaddingOffsetRequired(); if (offsetRequired) { paddingLeft += getLeftPaddingOffset(); } int left = mScrollX + paddingLeft; int right = left + mRight - mLeft - mPaddingRight - paddingLeft; int top = mScrollY + getFadeTop(offsetRequired); int bottom = top + getFadeHeight(offsetRequired); if (offsetRequired) { right += getRightPaddingOffset(); bottom += getBottomPaddingOffset(); } final ScrollabilityCache scrollabilityCache = mScrollCache; final float fadeHeight = scrollabilityCache.fadingEdgeLength; int length = (int) fadeHeight; // clip the fade length if top and bottom fades overlap // overlapping fades produce odd-looking artifacts if (verticalEdges && (top + length > bottom - length)) { length = (bottom - top) / 2; } // also clip horizontal fades if necessary if (horizontalEdges && (left + length > right - length)) { length = (right - left) / 2; } if (verticalEdges) { topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); drawTop = topFadeStrength * fadeHeight > 1.0f; bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); drawBottom = bottomFadeStrength * fadeHeight > 1.0f; } if (horizontalEdges) { leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); drawLeft = leftFadeStrength * fadeHeight > 1.0f; rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); drawRight = rightFadeStrength * fadeHeight > 1.0f; } saveCount = canvas.getSaveCount(); int solidColor = getSolidColor(); if (solidColor == 0) { final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; if (drawTop) { canvas.saveLayer(left, top, right, top + length, null, flags); } if (drawBottom) { canvas.saveLayer(left, bottom - length, right, bottom, null, flags); } if (drawLeft) { canvas.saveLayer(left, top, left + length, bottom, null, flags); } if (drawRight) { canvas.saveLayer(right - length, top, right, bottom, null, flags); } } else { scrollabilityCache.setFadeColor(solidColor); } // Step 3, draw the content if (!dirtyOpaque) onDraw(canvas); // Step 4, draw the children dispatchDraw(canvas); // Step 5, draw the fade effect and restore layers final Paint p = scrollabilityCache.paint; final Matrix matrix = scrollabilityCache.matrix; final Shader fade = scrollabilityCache.shader; if (drawTop) { matrix.setScale(1, fadeHeight * topFadeStrength); matrix.postTranslate(left, top); fade.setLocalMatrix(matrix); canvas.drawRect(left, top, right, top + length, p); } if (drawBottom) { matrix.setScale(1, fadeHeight * bottomFadeStrength); matrix.postRotate(180); matrix.postTranslate(left, bottom); fade.setLocalMatrix(matrix); canvas.drawRect(left, bottom - length, right, bottom, p); } if (drawLeft) { matrix.setScale(1, fadeHeight * leftFadeStrength); matrix.postRotate(-90); matrix.postTranslate(left, top); fade.setLocalMatrix(matrix); canvas.drawRect(left, top, left + length, bottom, p); } if (drawRight) { matrix.setScale(1, fadeHeight * rightFadeStrength); matrix.postRotate(90); matrix.postTranslate(right, top); fade.setLocalMatrix(matrix); canvas.drawRect(right - length, top, right, bottom, p); } canvas.restoreToCount(saveCount); // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); if (mOverlay != null && !mOverlay.isEmpty()) { mOverlay.getOverlayView().dispatchDraw(canvas); } }
可以看到取出我們的mScrollX和mScrollY然後在繪圖的各種translate繪圖這樣我們就看到了視圖裡面顯示的內容了,大體上的思路就是這樣。顯示地區執行個體現在結合一個例子來理解一下這個問題。我們直接上上一段很簡單的代碼。
LinearLayout linearLayout = new LinearLayout(this);linearLayout.setLayoutParams(new LayoutParams(2000, 2000));//這裡我把寬高設定大點好做測試因為My Phone是1920*1080所以設定得大一點linearLayout.setOrientation(LinearLayout.HORIZONTAL);TextView textView1 = new TextView(this);textView1.setText("hello i am text 1");textView1.setLayoutParams(new LayoutParams(1000, 2000));linearLayout.addView(textView1);TextView textView2 = new TextView(this);textView2.setText("hello i am text 2");textView2.setLayoutParams(new LayoutParams(1000, 2000));linearLayout.addView(textView2);setContentView(linearLayout);
就是在Activity的Oncreate函數裡面初始化我們的介面。我們給它一個很大的視圖,大得都超出了手機螢幕,然後我們跑一下看會有怎樣的效果。可以很清晰的看到我們的TextView2沒有顯示出來,這裡也就很明了了,因為超出了螢幕,然後我們重新加一句代碼。
LinearLayout linearLayout = new LinearLayout(this);linearLayout.setLayoutParams(new LayoutParams(2000, 2000));//這裡我把寬高設定大點好做測試因為My Phone是1920*1080所以設定得大一點linearLayout.setOrientation(LinearLayout.HORIZONTAL);TextView textView1 = new TextView(this);textView1.setText("hello i am text 1");textView1.setLayoutParams(new LayoutParams(1000, 2000));linearLayout.addView(textView1);TextView textView2 = new TextView(this);textView2.setText("hello i am text 2");textView2.setLayoutParams(new LayoutParams(1000, 2000));linearLayout.addView(textView2);linearLayout.scrollTo(1000, 0);//我們加了這一句代碼setContentView(linearLayout);
可以看到text2顯示完全了,這也很明顯因為我們把視圖向左滾動了。在後面講的UI控制項的系列教程這兩個scrollTo和scrollBy函數用得很頻繁,所以這裡從源頭把它給分析了一次,協助我們後面好理解。