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.我們的文字已經可以列印顯示到螢幕了.
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!