【GT-安卓應用開發之簡易文字廣告輪播】
阿新 • • 發佈:2018-12-16
前言:又是午休時間,今天寫一個簡單的文字輪播demo,主要由一個水平方向的TextView和一個豎直方向的ListView組成。安卓目前提供的TextView支援跑馬燈效果(修改幾個屬性即可),但是其有一個缺點就是一旦失去焦點,文字便不再滾動,自定義TextView修改幾個方法可以解決這一問題。ListView的滾動則可以利用TimerTask和ListView的smoothScrollBy實現。
介面:
關鍵程式碼:
1、TimeTask
class TimeTaskScroll extends TimerTask { private ListView listView; public TimeTaskScroll(Context context, ListView listView) { this.listView = listView; } private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { // 控制速度 listView.smoothScrollBy(2, 5); } }; @Override public void run() { Message msg = handler.obtainMessage(); handler.sendMessage(msg); } }
2、自定義TextView
@SuppressLint("AppCompatCustomView") public class ScrollTextView extends TextView { private boolean isMarqueeEnable = false; public ScrollTextView(Context context) { super(context); } public ScrollTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public ScrollTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setMarqueeEnable(boolean enable) { if (isMarqueeEnable != enable) { isMarqueeEnable = enable; if (enable) { setEllipsize(TextUtils.TruncateAt.MARQUEE); } else { setEllipsize(TextUtils.TruncateAt.END); } onWindowFocusChanged(enable); } } public boolean isMarqueeEnable() { return isMarqueeEnable; } @Override public boolean isFocused() { return isMarqueeEnable; } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(isMarqueeEnable, direction, previouslyFocusedRect); } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(isMarqueeEnable); } }