Android实现文字一个一个显示出来
生活随笔
收集整理的這篇文章主要介紹了
Android实现文字一个一个显示出来
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先上效果圖
可以采用自定義TextView的方式去實現,也可才用定時更新文字顯示,思路是讓TextView每隔一秒顯示以一個字符串(并非每一秒多出來一個漢字),那么就簡單了,可以開啟一個線程,那么線程主要方法如下:
public static void startTv(final int n) {new Thread(new Runnable() {@Override public void run() {try {final String stv = s.substring(0, n);//截取要填充的字符串 tv.post(new Runnable() {@Override public void run() {tv.setText(stv); }}); Thread.sleep(time);//休息片刻 nn = n + 1;//n+1;多截取一個 if (nn <= length) {//如果還有漢字,那么繼續開啟線程,相當于遞歸的感覺 startTv(nn); }} catch (InterruptedException e) {e.printStackTrace(); }}}).start(); } 完整代碼如下:
1.Activity
public class TiaoZiActivity extends Activity {private TextView textView; private String s = "天生我才必有用,千金散盡還福來--李白\n你挑著但,我騎著馬--唐僧\n年后打藍思科技卡死了減肥的 kjdsfkjsjkdsfj kjdflskjklfjsljdflsjkldfjsljdflsjdfkl";; private TiaoZiUtil tiaoziUtil; @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_tiaozi); textView = ((TextView) findViewById(R.id.tv_text)); tiaoziUtil = new TiaoZiUtil(textView, s, 100);//調用構造方法,直接開啟 }@Override protected void onDestroy() {super.onDestroy(); } } 2.工具類
public class TiaoZiUtil {private static TextView tv; private static String s; private static int length; private static long time; static int n = 0; private static int nn; public TiaoZiUtil(TextView tv, String s, long time) {this.tv = tv;//textview this.s = s;//字符串 this.time = time;//間隔時間 this.length = s.length(); startTv(n);//開啟線程 }public static void startTv(final int n) {new Thread(new Runnable() {@Override public void run() {try {final String stv = s.substring(0, n);//截取要填充的字符串 tv.post(new Runnable() {@Override public void run() {tv.setText(stv); }}); Thread.sleep(time);//休息片刻 nn = n + 1;//n+1;多截取一個 if (nn <= length) {//如果還有漢字,那么繼續開啟線程,相當于遞歸的感覺 startTv(nn); }} catch (InterruptedException e) {e.printStackTrace(); }}}).start(); }} 3.布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_text" android:layout_width="match_parent" android:layout_height="200dp" /> <TextView android:id="@+id/mytext" android:layout_width="match_parent" android:layout_height="200dp" /> </LinearLayout>
總結
以上是生活随笔為你收集整理的Android实现文字一个一个显示出来的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android CookieSyncMa
- 下一篇: Android 底部导航栏的简单实现-B