当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发中TextView 实现右上角跟随文本动态追加圆形红点

Android开发中TextView 实现右上角跟随文本动态追加圆形红点

2019年07月24日  | 移动技术网移动技术  | 我要评论

在一个比较坑的需求里,一段文字右上角需要追加一个圆形红点。最右侧有个金额,红点动态随着文字移动,然后各种摆布局,一下午坑死我了。后来果断放弃。然后就想试试直接自定义view来实现这个需求。

最坑的就是效果下面的第一种情况和第二种情况,就是这两种情况给逼的

image 

废话不说,开搞。

首先自定义个view 继承自 view 类

public class myviewandcircle extends view{
}

然后不用说了 ,直接飘红,必须要实现几个必要的方法了。

 public myviewandcircle(context context) {
    this(context,null);
    // todo auto-generated constructor stub
  }
  public myviewandcircle(context context, attributeset attrs) {
    this(context, attrs,0);
    // todo auto-generated constructor stub
  }
  public myviewandcircle(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);
}

然后就要想想这个需求到底是什么鬼了。

因为目前来说需要一个文本,还要有个红色圆形追加到文本域后边,那么有两种考虑了

- 1、文本+画圆

- 2、文本+图片

在这里我选第一种了,毕竟在view里边画个圆还是比较easy的,这种教程网上一搜一大把

那么既然有了目标

就可以写 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" />

如上 我们定义了==文本自身==, ==文本size==,==文本color==,为什么不定义圆形用的属性。那是因为。。。用不到,画个圆而已嘛,不用那么麻烦

next:

定义完了属性之后那么就要引入了:

public myviewandcircle(context 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, 16, getresources().getdisplaymetrics()));
        break;
      case r.styleable.custommyviewtitle_titlecolorview:
        mtextcolor = a.getint(attr, color.black);
        break;
      }
    }
    a.recycle();
  }

至此我们就将定义的控件中用的属性撸出来了,那么下面就开始撸代码了。

我贴个完整代码:代码里都加了注释来着

这个是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;
/**
 * 在一个比较坑的需求里,一段文字右上角需要追加一个圆形红点。最右侧有个金额,红点动态随着文字移动,然后各种摆布局,我去坑死我了。
 * 后来放弃了,就有了这个东西(⊙o⊙)…
 * 大神请加q群,大家一起探讨:123869487
 * @author 有点凉了
 *
 */
public class myviewandcircle extends view{
  private string mtext;//描述文字
  private int mtextcolor;//描述文字颜色
  private int mtextsize;//描述文字大小
  private rect rect;//控制边框 完整控件控制边框显示(宽高之类的)
  private rect mtextbound;//控制文本范围
  private rect mcircle;//控制红色圆点的位置
  private paint mpaint;//控制画笔
  private int mwidth;//宽
  private int mheight;//高
  private boolean isshow = true;
  rectf oval = null;//控制圆的边界
  public myviewandcircle(context context) {
    this(context,null);
    // todo auto-generated constructor stub
  }
  public myviewandcircle(context context, attributeset attrs) {
    this(context, attrs,0);
    // todo auto-generated constructor stub
  }
  public myviewandcircle(context 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, 16, getresources().getdisplaymetrics()));
        break;
      case r.styleable.custommyviewtitle_titlecolorview:
        mtextcolor = a.getint(attr, color.black);
        break;
      }
    }
    a.recycle();
    mpaint = new paint();//这里做初始化
    rect = new rect();
    mtextbound = new rect();
  }
  @override
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    // todo auto-generated method stub
    super.onmeasure(widthmeasurespec, heightmeasurespec);
    //在这里测量当前控件的宽和高,具体的意思请看
    /**
     * 系统帮我们测量的高度和宽度都是match_parnet,当我们设置明确的宽度和高度时,系统帮我们测量的结果就是我们设置的结果,
     * 当我们设置为wrap_content,或者match_parent系统帮我们测量的结果就是match_parent的长度。
     * 所以,当设置了wrap_content时,我们需要自己进行测量,即重写onmesure方法”:
     * 重写之前先了解measurespec的specmode,一共三种类型: 
     * exactly:一般是设置了明确的值或者是match_parent;
     * at_most:表示子布局限制在一个最大值内,一般为warp_content;
     * unspecified:表示子布局想要多大就多大,很少使用;
     */
    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);
    //这里就开始执行绘制了
    mpaint.settextsize(mtextsize);
    mpaint.gettextbounds(mtext, 0, mtext.length(), mtextbound);//计算文字所需要的宽度
    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);//这里在绘制最外侧布局的宽高
    mpaint.reset();
    //下面判断文本是否超出了父布局宽,然后分别作了设置
    if (mtextbound.width()>mwidth) {
//     文字超长展示
      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) {
        // 控制红色圆形大小
        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 {
      //正常情况
      mpaint.settextsize(mtextsize);
      canvas.drawtext(mtext, getpaddingleft(), (mheight/2 - mtextbound.height()/2)+mtextbound.height()-getpaddingbottom(), mpaint);
      mpaint.reset();
      if (isshow) {
        // 控制红色圆形大小
        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();
  }
}

这个是activity界面:

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("收拾收拾");
        textview.notification();
      }
    });
    button_show.setonclicklistener(new onclicklistener() {
      @override
      public void onclick(view v) {
        // todo auto-generated method stub
        textview.settitletext("我的天呐这个不科学,是不是,你说是不是,我说是的,我的天呐。这个东西是个什么鬼。啥玩意????????????????");
        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();
      }
    });
  }
}

这个当然就是activity布局了:

<?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="match_parent"
    android:layout_height="50dp"
    android:padding="3dp" >
    <com.qiao.view.myviewandcircle
      android:id="@+id/textview"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:padding="2dp"
      qiao:titlesizeview="13sp"
      qiao:titletextview="测试测试测试测试测试测试测试测试测试测试" />
  </linearlayout>
  <button
    android:id="@+id/button_show_one"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="设置短文字01" />
  <button
    android:id="@+id/button_show"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="设置长文字02" />
  <button
    android:id="@+id/button_show_circle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="设置圆显示" />
  <button
    android:id="@+id/button_show_circle_no"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="设置圆不显示" />
  <textview 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="\n 效果:\n 下面第一种效果是正常的,仅限于文字超短。如果文字超长,就成了第二种情况了 \n"/>
  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <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"
          android:layout_alignparentleft="true"
          android:ellipsize="end"
          android:singleline="true"
          android: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:gravity="right"
        android:text="套餐金额"
        android:textcolor="#555555"
        android:textsize="17sp" />
    </relativelayout>
  </linearlayout>
  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <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_one" >
        <textview
          android:id="@+id/textview_balance_service_name_one"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignparentleft="true"
          android:ellipsize="end"
          android:singleline="true"
          android:text="第二种情况:文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。文字超长这样。。"
          android:textcolor="#555555"
          android:textsize="15sp" />
        <imageview
          android:id="@+id/imageview_has_tag_one"
          android:layout_width="9dp"
          android:layout_height="9dp"
          android:layout_alignparenttop="true"
          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:layout_height="wrap_content"
        android:layout_alignparentright="true"
        android:gravity="right"
        android:text="套餐金额"
        android:textcolor="#555555"
        android:textsize="17sp" />
    </relativelayout>
  </linearlayout>
</linearlayout>

以上所述是小编给大家介绍的android开发中textview 实现右上角跟随文本动态追加圆形红点,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网