Custom TextView -- how to solve ViewGroup without calling the OnDraw method, textviewondraw

Source: Internet
Author: User

Custom TextView -- how to solve ViewGroup without calling the OnDraw method, textviewondraw

First, draw TextView to inherit from View: directly paste code

Public class TextView extends LinearLayout {private String mText; private int mTextSize = 18; private int mTextColor = Color. BLACK; private Paint mPaint; // the Paint brush of the text // The constructor will call // TextView TV = new TextView (this) when new is in the Code; public TextView (Context context) {this (context, null) ;}// use (CALL) public TextView (Context context, AttributeSet attrs) in layout {this (context, attrs, 0 );} // use (called) in layout, but there will be style public TextView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr ); // obtain the custom attribute TypedArray array = context. obtainStyledAttributes (attrs, R. styleable. textView); mText = array. getString (R. styleable. textView_yijiaText); mTextColor = array. getColor (R. styleable. textView_yijiaTextColor, mTextColor); // 18 18px 18sp mTextSize = array. getDimensionPixelSize (R. styleable. textView_yijiaTextSize, sp2px (mTextSize); // reclaim s array. recycle (); // initialize the Paint brush mPaint = new Paint (); mPaint. setAntiAlias (true); // sets the anti-sawtooth mPaint. setColor (mTextColor); // sets the paint brush color mPaint. setTextSize (mTextSize);}/*** custom View measurement method ** @ param widthMeasureSpec * @ param heightMeasureSpec */@ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); // The layout width and height are determined by this method. // specify the width and height of the control. You need to measure the value and obtain the width and height mode int widthMode = MeasureSpec. getMode (widthMeasureSpec); int heightMode = MeasureSpec. getMode (heightMeasureSpec); // 1. the specified value does not need to be calculated at this time. The given int width = MeasureSpec. getSize (widthMeasureSpec); int height = MeasureSpec. getSize (heightMeasureSpec); // 2. the value of if (widthMode = MeasureSpec. AT_MOST) {// The calculated width is related to the font length and the font size. Use a paint brush to measure Rect rect = new Rect (); // obtain the text's rectangular mPaint. getTextBounds (mText, 0, mText. length (), rect); width = rect. width ();} // 2. the value of if (heightMode = MeasureSpec. AT_MOST) {// The calculated width is related to the font length and the font size. Use a paint brush to measure Rect rect = new Rect (); // obtain the text's rectangular mPaint. getTextBounds (mText, 0, mText. length (), rect); height = rect. height ();} setMeasuredDimension (width, height);}/*** used to draw ** @ param canvas */@ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); Rect rect = new Rect (); mPaint. getTextBounds (mText, 0, mText. length (), rect); int dx = getWidth ()/2-rect. width ()/2; // the retrieval Center (fontMetrics. bottom-fontMetrics. top)/2 Paint. fontMetricsInt fontMetrics = mPaint. getFontMetricsInt (); int dy = (fontMetrics. bottom-fontMetrics. top)/2-fontMetrics. bottom; int baseLine = getHeight ()/2 + dy; canvas. drawText (mText, dx, baseLine, mPaint); Log. e ("TAG", "dy =" + dy + ", centerY =" + getHeight ()/2 + ", baseLine =" + baseLine );} private int sp2px (int spValue) {return (int) TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_SP, spValue, getResources (). getDisplayMetrics ());}}

Source code analysis: Why does ViewGroup not call onDraw? After setting the background, custom TextView can be displayed.

First, let's look at the source code of onDraw called in View.
 // Step 3, draw the content            if (!dirtyOpaque) onDraw(canvas);            // Step 4, draw the children            dispatchDraw(canvas);            // Overlay is part of the content and draws beneath Foreground            if (mOverlay != null && !mOverlay.isEmpty()) {                mOverlay.getOverlayView().dispatchDraw(canvas);            }            // Step 6, draw decorations (foreground, scrollbars)            onDrawForeground(canvas);

We can see that OnDraw is called when dirtyOpaque is false.

DirtyOpaque source code
 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;

We can see that it is controlled by privateFlags, that is, mPrivateFlags.

View Constructor
 computeOpaqueFlags();
ComputeOpaqueFlags (); view source code
  // Opaque if:        //   - Has a background        //   - Background is opaque        //   - Doesn't have scrollbars or scrollbars overlay        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;        } else {            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;        }        final int flags = mViewFlags;        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;        } else {            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;        }
View the ViewGroup constructor source code
 super(context, attrs, defStyleAttr, defStyleRes);        initViewGroup();        initFromAttributes(context, attrs, defStyleAttr, defStyleRes);
View initViewGroup source code
  if (!debugDraw()) {            setFlags(WILL_NOT_DRAW, DRAW_MASK);        }

The OnDraw in viewGrop is invisible due to setFlags.

Why: the background can be displayed after being set in viewgroup

Source code of setBackDrawable in view
   computeOpaqueFlags();        if (background == mBackground) {            return;        }

At this time, we found that the calculation was re-performed.

I personally think there are three solutions.

① Change onDraw to dispatchDraw ② set the background to transparent ③ you can check the source code and set the setFlags value.
public void setWillNotDraw(boolean willNotDraw) {        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);    }

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.