当前位置: 移动技术网 > IT编程>移动开发>Android > Android 自定义控件实现显示文字的功能

Android 自定义控件实现显示文字的功能

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

android 自定义控件实现显示文字的功能

自定义控件—–逐个显示文字

one goal ,one passion !

前言:

今天要实现的效果时.让我们的文字一个一个显示出来.上效果图吧:

实现原理:

1,拿到要显示的文字.

2,计算文字显示的速率
字体显示的速度 v = 总的字体长度 / 总的显示时间

3,将文字根据速率显示到控件上.

自定义view:

 public class printtextview extends textview {

  /**
   * 字体显示出来的时间
   */
  private int duration = 8000;

  public printtextview(context context) {
    this(context, null);
  }

  public printtextview(context context, attributeset attrs) {
    this(context, attrs, 0);
  }

  public printtextview(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);


  }


  public void printstring(string str) {


    if (str != null && str != "") {

      // 字符串的长度
      final int lenght = str.length();


      final char[] c = new char[str.length()];
      //将字符串转换成字符数组
      for (int i = 0; i < str.length(); i++) {
        c[i] = str.charat(i);
      }


      valueanimator animator = valueanimator.offloat(0, 1);
      animator.addupdatelistener(new valueanimator.animatorupdatelistener() {
        @override
        public void onanimationupdate(valueanimator animation) {

          // 字体显示的速度 v = 总的字体长度 / 总的显示时间
          float v = (float) lenght / (float) duration;
          // 动画执行速度
          float fraction = (float) animation.getanimatedvalue();
          //动画不同阶段字体应该显示的个数
          int s = (int) (v * fraction * duration);

          settext(c, 0, s);

        }
      });
      animator.setduration(duration);
      animator.start();
    }


  }


  }

跑起来:

 

 public class scaleactivity extends appcompatactivity {


  private printtextview print_text;
  string str = "我和你吻别,在无人的街.我和你吻别在狂乱的夜.这波给你103分," +
      "多一分宽容,多一分耐心,更重要的是多一分父爱.";

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_scale);
    initview();
  }




    print_text = (printtextview) findviewbyid(r.id.print_text);
    print_text.printstring(str);
  }
  }

r.layout.activity_scale布局文件

 <?xml version="1.0" encoding="utf-8"?>
  <linearlayout xmlns:android="http://  schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_margin="20dp"
  android:orientation="vertical"
  tools:context="com.example.customview.activity.scaleactivity">
 <com.example.customview.view.printtextview
    android:id="@+id/print_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
 />
 </linearlayout>

ok.我们的文字已经可以打印显示到屏幕了.

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

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

相关文章:

验证码:
移动技术网