android實現跑馬燈效果(可以實現兩個以上跑馬燈),android跑馬燈
本文用了繼承自TextView的MarqueeTextView來實現跑馬燈效果。原因是,跑馬燈效果是需要TextView擁有焦點才會跑動的。而有時候TextView獲得焦點會有點耗時,造成要等待一段時間跑馬燈效果才會出來。另外,系統預設時只有一個TextView處於focused狀態,而當頁面有不少於兩個跑馬燈時,用TextView就不好實現了。
MarqueeTextView類代碼:
public class MarqueeTextView extends TextView{public MarqueeTextView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}@Overrideprotected void onFocusChanged(boolean focused, int direction,Rect previouslyFocusedRect) {// TODO Auto-generated method stubsuper.onFocusChanged(focused, direction, previouslyFocusedRect);}@Overridepublic void onWindowFocusChanged(boolean hasWindowFocus) {// TODO Auto-generated method stubif(hasWindowFocus) super.onWindowFocusChanged(hasWindowFocus);}@Override@ExportedProperty(category = "focus")public boolean isFocused() {return true;}}
XML布局檔案相關代碼:
<com.barry.components.MarqueeTextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.0" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:freezesText="true" android:marqueeRepeatLimit="marquee_forever" android:paddingLeft="10dp" android:paddingRight="10dp" android:scrollHorizontally="true" android:singleLine="true" /><!--width設為具體大小也行。--!>
怎在同一個網頁中實現兩個跑馬燈效果
重名了
簡單方法,更名
把代碼再複製一遍,把複製的這個的所有demo,demo1,demo2,Marquee,MyMar都改個名字,比如都加上個2,如demo22。
再把第2個跑馬燈的demo,demo1改名,與上面改的名字一致。
TextView實現跑馬燈效果源碼
用自訂的TextViewpublic class AlwaysMarqueeTextView extends TextView { public AlwaysMarqueeTextView(Context context) { super(context); // TODO Auto-generated constructor stub } public AlwaysMarqueeTextView(Context context, AttributeSet attrs) { super(context, attrs); } public AlwaysMarqueeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean isFocused() { return true; } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { if (focused) super.onFocusChanged(focused, direction, previouslyFocusedRect); } @Override public void onWindowFocusChanged(boolean focused) { if (focused) super.onWindowFocusChanged(focused); }}xml<com.example.AlwaysMarqueeTextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_vertical"android:layout_marginLeft="10dp"android:ellipsize="marquee"android:focusable="true"android:focusableInTouchMode="true"android:marqueeRepeatLimit="marquee_forever"android:singleLine="true"android:text="這裡是天翔燈飾的公告內容....運用文字跑馬燈效果....運用文字跑馬燈效果....運用文字跑馬燈效果....運用文字跑馬燈效果....運用文字跑馬燈效果....運用文字跑馬燈效果" />