文字超寬時自動橫向滾動,循環播放:

在 XML 佈局中為 `TextView` 設定以下屬性:
<TextView
android:id="@+id/text1"
android:layout_width="80dp"
android:layout_height="40dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:singleLine="true"
android:textColor="#0551A5"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_centerInParent="true" />
| 屬性 | 作用 |
|---|---|
ellipsize="marquee" | 啟用跑馬燈效果 |
marqueeRepeatLimit="marquee_forever" | 無限循環(也可填數字指定次數) |
focusable="true" | 允許獲取焦點(滾動前提) |
focusableInTouchMode="true" | 觸摸模式下也能獲取焦點 |
scrollHorizontally="true" | 允許水平滾動 |
singleLine="true" | 強制單行顯示(必要條件) |
public class MyActivity extends Activity {
private TextView text1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text1 = (TextView) findViewById(R.id.text1);
text1.setText("春光無限好,只是近黃昏………………");
}
}
只要文字寬度超過 `layout_width`,且 View 獲得焦點,跑馬燈即自動啟動。
(原文提供下載連結,此處略)