如何在 Android 中實現跑馬燈文字?


本例演示如何在 Android 中實現跑馬燈文字。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到“檔案 ⇒ 新專案”,然後填寫所有必需的詳細資訊以建立一個新專案。

步驟 2 − 向 res/layout/activity_main.xml 新增以下程式碼。

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/text"
      android:textSize = "20dp"
      android:textAlignment = "center"
      android:layout_width = "match_parent"
      android:ellipsize = "marquee"
      android:fadingEdge = "horizontal"
      android:marqueeRepeatLimit = "marquee_forever"
      android:scrollHorizontally = "true"
      android:textColor = "#ff4500"
      android:text = "Simple application that shows how to use marquee, with a long text"
      android:layout_height = "wrap_content"
      android:singleLine = "true" />
</RelativeLayout>

在以上程式碼中,我們採用了文字檢視,並且省略了屬性為跑馬燈的屬性,如下所示 -

android:ellipsize = "marquee"
android:fadingEdge = "horizontal"
android:marqueeRepeatLimit = "marquee_forever"
android:scrollHorizontally = "true"
android:singleLine = "true"

步驟 3 − 向 src/MainActivity.java 新增以下程式碼

package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView txt = findViewById(R.id.text);
      txt.setSelected(true);
   }
}

我們嘗試執行你的應用程式。我假設你已將你的實際 Android 移動裝置連線到計算機。要從 Android Studio 執行該應用,請開啟一個專案活動檔案,然後單擊工具欄上的執行   圖示。選擇你的移動裝置作為一項選項,然後檢視會顯示預設螢幕的移動裝置 −

在以上結果中,文字檢視將從右向左滾動,並帶滾動動畫。

點選 此處 下載專案程式碼

更新於:2019 年 7 月 30 日

2K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.