Android 自定義控件實現(xiàn)顯示文字的功能
Android 自定義控件實現(xiàn)顯示文字的功能
自定義控件—–逐個顯示文字
ONE Goal ,ONE Passion !
前言:
今天要實現(xiàn)的效果時.讓我們的文字一個一個顯示出來.上效果圖吧:

實現(xiàn)原理:
1,拿到要顯示的文字.
2,計算文字顯示的速率
字體顯示的速度 v = 總的字體長度 / 總的顯示時間
3,將文字根據(jù)速率顯示到控件上.
自定義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()];
//將字符串轉(zhuǎn)換成字符數(shù)組
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;
// 動畫執(zhí)行速度
float fraction = (float) animation.getAnimatedValue();
//動畫不同階段字體應(yīng)該顯示的個數(shù)
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.我們的文字已經(jīng)可以打印顯示到屏幕了.
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Android7.0指紋服務(wù)FingerprintService實例介紹
這篇文章主要介紹了Android7.0指紋服務(wù)FingerprintService介紹,需要的朋友可以參考下2018-01-01
源碼淺析Android中內(nèi)存泄漏檢測工具Leakcanary的使用
大名鼎鼎的 Leakcanary 想必作為 Android 開發(fā)都多多少少接觸過,新版本的 Leakcanary 也用 Kotlin 重寫了一遍,最近詳細查看了下源碼,就來和大家簡單分享一下2023-04-04
Android System fastboot 介紹和使用教程
Fastboot是Android快速升級的一種方法,Fastboot的協(xié)議fastboot_protocol.txt在源碼目錄./bootable/bootloader/legacy下可以找到,本文給大家介紹Android System fastboot 介紹和使用教程,感興趣的朋友一起看看吧2024-01-01
Android DrawLayout結(jié)合ListView用法實例
這篇文章主要介紹了Android DrawLayout結(jié)合ListView用法實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09

