1. 概述
在 Android
開發(fā)中撑瞧,有時候需要實現(xiàn)文本在 TextView
上的自動滾動效果环鲤,比如顯示公告等脂、滾動字幕等裁奇。本文將通過以下步驟介紹如何實現(xiàn) Android TextView
的自動滾動桐猬。
2. 實現(xiàn)流程
下面是實現(xiàn) Android TextView
自動滾動的流程:
3. 具體步驟與代碼實現(xiàn)
步驟1:創(chuàng)建 TextView
首先麦撵,在布局文件中創(chuàng)建一個 TextView
控件刽肠,用于顯示滾動的文本內(nèi)容溃肪。
<TextView
android:id="@+id/scrollingTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:text="這是一個自動滾動的TextView"
android:textSize="20sp" />
步驟2:獲取 TextView
的 LayoutParams
接下來,在代碼中獲取 TextView的LayoutParams
音五,用于設(shè)置滾動效果的相關(guān)屬性惫撰。
TextView scrollingTextView = findViewById(R.id.scrollingTextView);
LayoutParams layoutParams = scrollingTextView.getLayoutParams();
步驟3:設(shè)置 LayoutParams 屬性
將 LayoutParams
的屬性設(shè)置為可滾動。
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
scrollingTextView.setLayoutParams(layoutParams);
步驟4:設(shè)置 TextView 文本
設(shè)置 TextView
顯示的文本內(nèi)容躺涝。
scrollingTextView.setText("這是一個自動滾動的TextView");
步驟5:將 TextView 添加到布局中
將 TextView
添加到布局中顯示厨钻。
LinearLayout layout = findViewById(R.id.layout);
layout.addView(scrollingTextView);
步驟6:設(shè)置 TextView
滾動效果
設(shè)置 TextView
的滾動效果,使其自動滾動起來坚嗜。
scrollingTextView.setSelected(true);
scrollingTextView.setSingleLine(true);
scrollingTextView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
scrollingTextView.setMarqueeRepeatLimit(-1);
scrollingTextView.setFocusable(true);
scrollingTextView.setFocusableInTouchMode(true);
scrollingTextView.requestFocus();
scrollingTextView.requestFocusFromTouch();
其實夯膀,主要是這句話:scrollingTextView.setSelected(true);
在XML布局里面設(shè)置好屬性,之后在代碼里加上上面那句話苍蔬,就可以了诱建。
4. 代碼解析
下面對上述代碼進行解析:
5. 狀態(tài)圖
下面是 TextView
自動滾動的狀態(tài)圖:
6. 最后
轉(zhuǎn)載自android textview 自動滾動