android中TextView的文字实现动态效果,走马灯效果,闪烁效果

时间:2023-02-08 20:02:37

笔者在学习android的过程中曾遇到过一个比较头疼的问题——如何让文本实现走马灯的效果,在起初我和大家一样想在网上找到一点资料,可是当我在茫茫网际中搜寻了几个小时之后发现的结果却是非常恼火的,提问的一大堆却没有回答的,于是我开始自己的专研道路,笔者是一个android的菜鸟级人物,而且是非常菜的那种。在对android自带的例子的学习中我渐渐明白了如何实现走马灯效果了。以下是我自己的一段代码,如有不正确之处请多多指正。

 
package irdc.ScrollingText;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ScrollingText extends Activity
{
  public TextView t1;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t1= (TextView) findViewById(R.id.t1);
    t1.setText("哈哈我的跑马灯程序接下来是歌词呵呵:沉鱼落雁,闭月羞花,美的无处藏,人在身旁,如沐春光");
    t1.setTextSize(30);
    t1.setHorizontallyScrolling(true);
    t1.setFocusable(true);

  }
}
       在这段程序中我设置了t1的焦点为真(意思为焦点在t1上),同事我设置了t1的文本显示能超过其显示区域( t1.setHorizontallyScrolling(true ) 设置的这行的目的是为了不让程序自动给文本折行,使之为单行),当然这些属性你都可以在XML文件中定义。接下来我们看看main.xml文件。
 
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget35"
android:layout_;fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/black"
xmlns:android=" http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/t1"
android:layout_width ="100px"//此处为文本显示区域的宽度此值必须比你的文本宽度要小否则是没有效果的
android:layout_height="wrap_content"
android:text="@string/str_id"
android:textColor="@drawable/green"
android:layout_x="61px"
android:layout_y="69px"
android:scrollX="2px"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"

>
</TextView>
<ViewStub android:layout_y="221dip" android:layout_;wrap_content" android:layout_x="103dip" android:id="@+id/ViewStub01" android:layout_height="wrap_content"></ViewStub>
</AbsoluteLayout>
       大家注意到在TextView中我添加了三行蓝色的字段,其中singleLine表示TextView中文本为单行文本如果你在你的程序中设置了 setHorizontallyScrolling(true)在这你可以不写了,接下来就是我们的关键之处了 ellipsize="marquee" 此语句表示我们将TextView设置为了一个走马灯,marqueeRepeatLimit="marquee_forever"  表示走马灯的滚动效果重复的次数,你可以填一个自然数。
好了接下了编译试试。
 
     PS:闪烁文字的制作
        很多游戏里都有闪烁的文字,比如像一打开一个应用,第一个页面往往是大幅的游戏画报,然后下面有个闪烁的“任意键继续”或者“TOUCH THE SCREEN”,这个怎么做呢?我考虑之后想到了可以用定时器实现,每300ms更换一次文字颜色就行了,代码如下,如果有更好的办法也希望能发邮件告诉我一下,多谢!
    private boolean change = false;
    TextView touchScreen = (TextView)findViewById(R.id.touchscreen);//获取页面textview对象
    Timer timer = new Timer();
    timer.schedule(task,1,300);  //参数分别是delay(多长时间后执行),duration(执行间隔)
    TimerTask task = new TimerTask(){  
        public void run() {  
            runOnUiThread(new Runnable(){  
            public void run() {  
       if(change){
        change = false;
        touchScreen.setTextColor(Color.TRANSPARENT); //这个是透明,=看不到文字
       }else{
        change = true;
        touchScreen.setTextColor(Color.RED);
       }  
            }});  
            }  
    };