Android Development TextView Implementation of the upper right corner follow text dynamic append circular red dot _android

Source: Internet
Author: User
Tags drawtext stub visibility xmlns

In a comparison pit, the upper-right corner of a piece of text needs to be appended with a circular red dot. The right side has an amount, red dot dynamic with the text moving, and then various pendulum layout, one afternoon pit dead me. Then decisively gave up. Then try to customize the view directly to achieve this requirement.

The most pit is the effect of the first situation and the second situation, is the two situations to force

Don't talk nonsense, open a mess.

First customize view inherits from view class

public class Myviewandcircle extends view{
}

Then needless to say, the direct drift red, must realize several necessary methods.

 Public Myviewandcircle {This
    (context,null);
    TODO auto-generated constructor stub
  } public
  myviewandcircle (context context, AttributeSet attrs) {
    This is (context, attrs,0);
    TODO auto-generated constructor stub
  } public
  myviewandcircle (context, AttributeSet attrs, int defstyleattr) {
    Super (context, attrs, defstyleattr);
}

And then you have to think about what the hell that demand is.

Because at the moment you need a text and a red circle is appended to the text field, there are two ways to think about it.

-1, text + draw round

-2, text + pictures

Here I choose the first kind, after all, in the view inside a circle or relatively easy, this tutorial online search a lot of

So now that you have a goal,

We can write Attrs,

<declare-styleable name= "Custommyviewtitle" >
    <attr name= "Titletextview"/> <attr name=
    " Titlesizeview "/>
    <attr name=" Titlecolorview "/>
  </declare-styleable>
  <attr name=" Titletextview "format=" string "/>
  <attr name=" Titlecolorview "format=" Color "/>" <attr name=
  " Titlesizeview "format=" Dimension "/>

As above we have defined = = text itself = = text size==,== text color==, why not define the properties of the circle. That's because ... You can't use it, draw a circle, don't bother.

Next

Once you have defined the attributes, you will introduce:

Public myviewandcircle (context, AttributeSet attrs, int defstyleattr) {
    Super (context, attrs, defstyleattr) ;
    TODO auto-generated Constructor stub
    TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.custommyviewtitle, defstyleattr, 0);
    int n = a.getindexcount ();
    for (int i = 0; i < n; i++) {
      int attr = A.getindex (i);
      Switch (attr) {case
      R.styleable.custommyviewtitle_titletextview:
        mtext = a.getstring (attr);
        break;
      Case R.styleable.custommyviewtitle_titlesizeview:
        mtextsize = A.getdimensionpixeloffset (attr, (int) Typedvalue.applydimension (TYPEDVALUE.COMPLEX_UNIT_SP, Getresources (). Getdisplaymetrics ()));
        break;
      Case R.styleable.custommyviewtitle_titlecolorview:
        mtextcolor = A.getint (attr, color.black);
        break;
      }
    }
    A.recycle ();
  }

So now we're going to use the properties of the defined controls, and then we'll start to masturbate.

I put a complete code: The code is all annotated.

This is the code for the view:

Package Com.qiao.view;
Import Com.qiao.Utils.Utils;
Import COM.QIAO.SELFVIEW.R;
Import com.qiao.selfview.r.styleable;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.graphics.Bitmap;
Import Android.graphics.Canvas;
Import Android.graphics.Color;
Import Android.graphics.Paint;
Import Android.graphics.Rect;
Import Android.graphics.RectF;
Import Android.text.TextPaint;
Import Android.text.TextUtils;
Import Android.util.AttributeSet;
Import Android.util.TypedValue;
Import Android.view.View;
Import Android.view.View.MeasureSpec; /** * In a comparison pit demand, a paragraph of text in the upper right corner needs to append a circular red dot.
 There is an amount on the right, red dot dynamic with the text moving, and then various pendulum layout, I go to pit dead me. * Then give up, there is this thing (⊙o⊙) ... * great god please add Q Group, we discuss together: 123869487 * @author a little cold * * * * * * * * * public class Myviewandcircle extends view{Priva Te String mtext;//descriptive text private int mtextcolor;//description text color private int mtextsize;//Description text size private Rect rect;//control border complete control
  Border display (wide high) private Rect mtextbound;//control text range private Rect mcircle;//control the position of the red dot private Paint mpaint;//control brushprivate int mwidth;//wide private int mheight;//High Private Boolean isshow = true;
    RECTF Oval = null;//The bounds of the control Circle public myviewandcircle (the context context) {this (context,null); TODO auto-generated Constructor stub} public myviewandcircle (context context, AttributeSet Attrs) {This (conte
    XT, attrs,0); TODO auto-generated Constructor stub} public myviewandcircle (context, AttributeSet attrs, int defstyleattr
    ) {Super (context, attrs, defstyleattr); TODO auto-generated constructor stub TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.STYLEABLE.CU
    Stommyviewtitle, defstyleattr, 0);
    int n = a.getindexcount ();
      for (int i = 0; i < n; i++) {int attr = A.getindex (i);
        Switch (attr) {Case r.styleable.custommyviewtitle_titletextview:mtext = a.getstring (attr);
      Break Case r.styleable.custommyviewtitle_titlesizeview:mtextsize = A.getdimensionpixeloffset (attr, (int) TypedVaLue.applydimension (TYPEDVALUE.COMPLEX_UNIT_SP, Getresources (). Getdisplaymetrics ()));
      Break
        Case R.styleable.custommyviewtitle_titlecolorview:mtextcolor = A.getint (attr, Color.Black);
      Break
    } a.recycle ();
    Mpaint = new Paint ()//here do initialize rect = new rect ();
  Mtextbound = new Rect (); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//TODO auto-generated method
    Stub super.onmeasure (Widthmeasurespec, Heightmeasurespec); Here to measure the width and height of the current control, please see/** * system to help us measure the height and width are match_parnet, when we set a clear width and height, the system to help us measure the result is the result we set, * when we set to Wrap_c
     Ontent, or match_parent system to help us measure the result is the length of the match_parent. * So, when we set the wrap_content, we need to measure ourselves, that is, to rewrite the Onmesure method: * Before rewriting the specmode of Measurespec, there are three types: * Exactly: Generally set a definite value or
     Match_parent;
     * At_most: Indicates that the child layout is limited to a maximum value, generally warp_content;
     * UNSPECIFIED: Indicates how big the child layout wants, rarely used;
  * * int specmode = Measurespec.getmode (Widthmeasurespec);  int spensize = measurespec.getsize (Widthmeasurespec);
    if (Specmode ==measurespec.exactly) {mwidth = spensize;
    } Specmode = Measurespec.getmode (Heightmeasurespec);
    Spensize = Measurespec.getsize (Heightmeasurespec);
    if (specmode==measurespec.exactly) {mheight = spensize;
      }else {mpaint.settextsize (16);
      Mpaint.gettextbounds (mtext, 0, Mtext.length (), mtextbound);
      float textHeight = Mtextbound.height ();
      int desired = (int) (Getpaddingtop () +textheight+getpaddingbottom ());
    Mheight = desired;
  } setmeasureddimension (Mwidth, mheight);
    @Override protected void OnDraw (Canvas Canvas) {//TODO auto-generated Method Stub Super.ondraw (Canvas);
    Here we begin to perform the drawing of Mpaint.settextsize (Mtextsize);
    Mpaint.gettextbounds (mtext, 0, Mtext.length (), mtextbound); The width required for the calculation of the text Mpaint.setcolor (Color.Blue);
    Mpaint.setstyle (Paint.Style.STROKE);
    Mpaint.settextsize (mtextsize); Utils.mlogerror ("==-->recT.width () "+rect.width ());
    rect.left=0;
    Rect.top=0;
    Rect.right=getmeasuredwidth ();
    Rect.bottom = Getmeasuredheight ();
    Canvas.drawrect (rect, mpaint);//Here in drawing the most lateral layout of the wide-high mpaint.reset ();
      The following determines whether the text is outside the parent layout width and then sets the IF (Mtextbound.width () >mwidth) {//Text long display mpaint.settextsize (mtextsize);
      Textpaint paint = new Textpaint (mpaint); String msg = textutils.ellipsize (Mtext, Paint, (float) mwidth-getpaddingleft ()-Getpaddingright (), Textutils.
      truncateat.end). toString ();
      Canvas.drawtext (MSG, Getpaddingleft (), MHEIGHT/2-Getpaddingtop () +mtextbound.height ()/2, mpaint);
      Mpaint.reset ();
        if (isshow) {//controls the red circle size Mpaint.setantialias (true);
        Mpaint.setcolor (Color.parsecolor ("#FE4D3D"));
        Oval = new RECTF ();
        Oval.left = Getmeasuredwidth ()-30;
        Oval.right=getmeasuredwidth ();
        Oval.top=getmeasuredheight ()/2-mtextbound.height ()/2-30; Oval.bottom=getmeasuredheighT ()/2-mtextbound.height ()/2;
        Canvas.drawarc (Oval, 0, 360, true, Mpaint);
      Mpaint.reset ();
      }}else {//normal mpaint.settextsize (mtextsize); Canvas.drawtext (Mtext, Getpaddingleft (), (MHEIGHT/2-Mtextbound.height ()/2) +mtextbound.height ()-getPaddingBottom (
      ), Mpaint);
      Mpaint.reset ();
        if (isshow) {//controls the red circle size Mpaint.setantialias (true);
        Mpaint.setcolor (Color.parsecolor ("#FE4D3D"));
        Oval = new RECTF ();
        Oval.left = Mtextbound.width () +getpaddingright ();
        Oval.right=mtextbound.width () +getpaddingright () +30;
        Oval.top=getmeasuredheight ()/2-mtextbound.height ()/2-30;
        Oval.bottom=getmeasuredheight ()/2-mtextbound.height ()/2;
        Canvas.drawarc (Oval, 0, 360, true, Mpaint);
      Mpaint.reset ();
  }} public void Settitletext (String mtext) {this.mtext = Mtext;
  } public void Setisvisiable (Boolean isshow) {this.isshow = Isshow; } public void NotifIcation () {invalidate (); }
}

This is the activity interface:

Package Com.qiao.selfview;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;
Import com.qiao.base.BaseActivity;
Import com.qiao.view.MyViewAndCircle;
  public class Myselfview extends baseactivity{private Button button_show;
  Private Button Button_show_one;
  Private Button button_show_circle;
  Private Button button_show_circle_no;
  Private Myviewandcircle TextView; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.oncreate
    (savedinstancestate);
    Setcontentview (R.layout.activity_myselfview);
    TextView = (myviewandcircle) Findviewbyid (R.id.textview);
    Button_show_one = (Button) Findviewbyid (R.id.button_show_one);
    Button_show = (Button) Findviewbyid (r.id.button_show);
    Button_show_circle = (Button) Findviewbyid (r.id.button_show_circle); Button_show_circle_no = (Button) Findviewbyid (r.id.button_sHOW_CIRCLE_NO); Button_show_one.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//
        TODO auto-generated Method Stub textview.settitletext ("Tidy up");
      Textview.notification ();
    }
    });  Button_show.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated method Stub Textview.settitletext ("My God, this is not science, is not, you say is not, I said yes, my God.") What a ghost this thing is. What thing?????????????????????????
        ");
      Textview.notification ();
    }
    });
        Button_show_circle.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {
        TODO auto-generated Method Stub textview.setisvisiable (true);
      Textview.notification ();
    }
    });
        Button_show_circle_no.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { TODO auto-generated Method Stub textview.setisvisiablE (false);
      Textview.notification ();
  }
    }); }
}

This is, of course, the activity layout:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/"
  Android "xmlns:qiao=" Http://schemas.android.com/apk/res/com.qiao.selfview "android:layout_width=" Match_parent " android:layout_height= "match_parent" android:orientation= "vertical" > <linearlayout android:layout_width= "ma Tch_parent "android:layout_height=" 50DP "android:padding=" 3DP "> <com.qiao.view.myviewandcircle an Droid:id= "@+id/textview" android:layout_width= "match_parent" android:layout_height= "Match_parent" Androi d:padding= "2DP" qiao:titlesizeview= "13SP" qiao:titletextview= "test test test testing test"/> </linearlayout&
  Gt <button android:id= "@+id/button_show_one" android:layout_width= wrap_content "android:layout_height=" Wrap_c Ontent "android:text=" set the short word "/> <button android:id=" @+id/button_show "android:layout_width=" Wrap_con Tent "android:layout_height="Wrap_content" android:text= "Set long text"/> <button android:id= "@+id/button_show_circle" Android:layout_w Idth= "Wrap_content" android:layout_height= "Wrap_content" android:text= "Set Circle to display"/> <button android:id= "@ +id/button_show_circle_no "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:te" xt= "Set circle does not show"/> <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" and Roid:text= "\ n effect: \ n The following effect is normal, limited to short text. If the text is too long, it becomes the second case. \ n "/> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_conte
      NT "> <relativelayout android:layout_width=" match_parent "android:layout_height=" Wrap_content ">
        <relativelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:layout_toleftof= "@+id/amount" > <textview android:id= "@+id/textview_balancE_service_name "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "and Roid:layout_alignparentleft= "true" android:ellipsize= "End" android:singleline= "true" Android
          : text= "First case: Short text" android:textcolor= "#555555" android:textsize= "15sp"/> <imageview
          Android:id= "@+id/imageview_has_tag" android:layout_width= "9DP" android:layout_height= "9DP" Android:layout_alignparenttop= "true" android:layout_marginleft= "3DP" android:layout_torightof= "@+ Id/textview_balance_service_name "android:src=" @drawable/from_shop_sell "android:visibility=" visible " /> </RelativeLayout> <textview android:id= "@+id/amount" android:layout_width= "wrap" _content "android:layout_height=" Wrap_content "android:layout_alignparentright=" true "Android:grav Ity= "Right" AndrOid:text= "Package Amount" android:textcolor= "#555555" android:textsize= "17sp"/> </RelativeLayout> &l t;/linearlayout> <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" &G
    T <relativelayout android:layout_width= "match_parent" android:layout_height= "wrap_content" > <Rel Ativelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:layou
          t_toleftof= "@+id/amount_one" > <textview android:id= "@+id/textview_balance_service_name_one" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_alignpare Ntleft= "true" android:ellipsize= "End" android:singleline= "true" android:text= the second case: The text is super long. 。 The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... The text is super long so ... "Android:textcolOr= "#555555" android:textsize= "15sp"/> <imageview android:id= "@+id/imageview_has_tag_on E "android:layout_width=" 9DP "android:layout_height=" 9DP "android:layout_alignparenttop=" Tru
          E "android:layout_marginleft=" 3DP "android:layout_torightof=" @+id/textview_balance_service_name_one " 
      android:src= "@drawable/from_shop_sell" android:visibility= "visible"/> </RelativeLayout> <textview android:id= "@+id/amount_one" android:layout_width= "Wrap_content" android:layou t_height= "Wrap_content" android:layout_alignparentright= "true" android:gravity= "right" Android:tex T= "Package Amount" android:textcolor= "#555555" android:textsize= "17sp"/> </RelativeLayout> </line Arlayout> </LinearLayout>

The above is a small set to introduce the Android development in the TextView implementation of the upper right corner follow the text to add a circular red dot, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.