Android實(shí)現(xiàn)搜索框文字輪播控件
先看效果圖:

實(shí)現(xiàn)思路
添加依賴:
implementation 'com.haowen:textbanner:1.0.4'1、想要達(dá)到輪播效果,兩個(gè)View交替出現(xiàn)即可,既然是兩個(gè)View那么就需要一個(gè)父容器(TextBanner繼承FrameLayout):
public class TextBanner extends FrameLayout {/*** 兩個(gè)View交替出現(xiàn)*/private View viewFirst, viewSecond;}
2、間隔性就用Handler的postDelayed來實(shí)現(xiàn)就行了,為了防止內(nèi)存泄漏,這里采用WeakHandler
mHandler.postDelayed(task, mDelayTime);/*** 輪播的定時(shí)任務(wù):當(dāng)頁數(shù)大于1時(shí)輪播*/private Runnable task = new Runnable() {@Overridepublic void run() {updateTipAndPlayAnimation();mHandler.postDelayed(this, mDelayTime);}};
3、交替出現(xiàn)的動(dòng)畫(TextBanner只用了一個(gè)簡(jiǎn)單的Y方向平移動(dòng)畫,并不支持動(dòng)畫設(shè)置,因?yàn)槲矣X得沒必要花里胡哨的,如果后期有需要,可以考慮提示自定義)
/*** 生成動(dòng)畫** @param fromYValue 起始值* @param toYValue 結(jié)束值* @return 動(dòng)畫*/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ù)設(shè)置適配器,這里采用Adapter的形式(看方法名應(yīng)該很好理解,似曾相識(shí)):
onCreateView設(shè)置顯示View
getCount數(shù)據(jù)個(gè)數(shù)
onBindViewData給View設(shè)置數(shù)據(jù)顯示
notifyDataChange數(shù)據(jù)更新通知
/*** 數(shù)據(jù)適配器*/public abstract static class Adapter {/*** 數(shù)據(jù)更新觀察這*/private Observable mObservable;/*** 注冊(cè)數(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個(gè)數(shù)** @return Item個(gè)數(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);}
源碼地址:
https://github.com/HaowenLee/TextBanner
到這里就結(jié)束啦。
評(píng)論
圖片
表情
