筆者在學習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);
}
}});
}
};