image
閑話不多說,先看效果圖:
image
實現(xiàn)思路
依賴: implementation 'com.haowen:textbanner:1.0.4'
1:想要達到輪播效果,兩個View交替出現(xiàn)即可,既然是兩個View那么就需要一個父容器(TextBanner繼承FrameLayout):
public class TextBanner extends FrameLayout {
/**
* 兩個View交替出現(xiàn)
*/
private View viewFirst, viewSecond;
}
2:間隔性就用Handler的postDelayed來實現(xiàn)就行了笔呀,為了防止內(nèi)存泄漏,這里采用WeakHandler
mHandler.postDelayed(task, mDelayTime);
/**
* 輪播的定時任務:當頁數(shù)大于1時輪播
*/
private Runnable task = new Runnable() {
@Override
public void run() {
updateTipAndPlayAnimation();
mHandler.postDelayed(this, mDelayTime);
}
};
3:交替出現(xiàn)的動畫(TextBanner只用了一個簡單的Y方向平移動畫髓需,并不支持動畫設置许师,因為我覺得沒必要花里胡哨的,如果后期有需要,可以考慮提示自定義)
/**
* 生成動畫
*
* @param fromYValue 起始值
* @param toYValue 結束值
* @return 動畫
*/
private Animation newAnimation(float fromYValue, float toYValue) {
Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue);
anim.setDuration(mDuration);
anim.setInterpolator(new DecelerateInterpolator());
return anim;
}
5:數(shù)據(jù)設置適配器微渠,這里采用Adapter的形式(看方法名應該很好理解搭幻,似曾相識):
onCreateView設置顯示View
getCount數(shù)據(jù)個數(shù)
onBindViewData給View設置數(shù)據(jù)顯示
-
notifyDataChange數(shù)據(jù)更新通知
/** * 數(shù)據(jù)適配器 */ public abstract static class Adapter { /** * 數(shù)據(jù)更新觀察這 */ private Observable mObservable; /** * 注冊數(shù)據(jù)更新觀察 * * @param observable 數(shù)據(jù)更新觀察 */ private void registerObservable(Observable observable) { this.mObservable = observable; } /** * 通知數(shù)據(jù)更新 */ public void notifyDataChange() { if (mObservable != null) { mObservable.onChange(); } } /** * Item個數(shù) * * @return Item個數(shù) */ public abstract int getCount(); /** * View生成 * * @param parent 父容器 * @return Item的View */ public abstract View onCreateView(@NonNull ViewGroup parent); /** * 數(shù)據(jù)綁定View * * @param convertView 內(nèi)容View * @param position 位置 */ public abstract void onBindViewData(@NonNull View convertView, int position); }