Android消息公告上下滚动切换轮播实现
自定义控件
通过继承TextSwitcher实现
直接上代码
public class NoticesSwitcher extends TextSwitcher implements ViewSwitcher.ViewFactory {private Context mContext;private List<Notice> mData;private final long DEFAULT_TIME_SWITCH_INTERVAL = 1000;//1sprivate long mTimeInterval = DEFAULT_TIME_SWITCH_INTERVAL;private int mCurrentIndex = 0;private Notice curNotice;public NoticesSwitcher(Context context, AttributeSet attrs) {super(context, attrs);this.mContext = context;setFactory(this);}public NoticesSwitcher setInAnimation(int animationResId){Animation animation = AnimationUtils.loadAnimation(this.mContext, animationResId);setInAnimation(animation);return this;}public NoticesSwitcher setOutAnimation(int animationResId){Animation animation = AnimationUtils.loadAnimation(this.mContext, animationResId);setOutAnimation(animation);return this;}/*** 通知/公告数据绑定* @param data* @return*/public NoticesSwitcher bindData(List<Notice> data) {this.mData = data;return this;}public void startSwitch(long timeInterval){this.mTimeInterval = timeInterval;mSwitchHandler.removeMessages(0);if (mData != null && mData.size() > 0) {mSwitchHandler.sendEmptyMessage(0);}else{throw new RuntimeException("data is empty");}}/*** 工厂类中创建TextView供给TextSwitcher使用* @return*/@Overridepublic View makeView() {LayoutInflater inflater = LayoutInflater.from(mContext);TextView view = (TextView) inflater.inflate(R.layout.item_notice_switcher, null);view.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (curNotice != null) {// 跳转详情}}});return view;}private Handler mSwitchHandler = new Handler(){@Overridepublic void dispatchMessage(Message msg) {super.dispatchMessage(msg);int index = mCurrentIndex % mData.size();curNotice = mData.get(index);setText(mData.get(index).title);mCurrentIndex++;if (mData.size() > 1) {sendEmptyMessageDelayed(0, mTimeInterval);}}};}
public class Notice {public String title;public Notice() {}public Notice(String title) {this.title = title;}
}
使用
<com.anyixing.etc.staff.view.NoticesSwitcherandroid:id="@+id/notices_switcher"android:layout_width="match_parent"android:layout_height="wrap_content"/>
List<Notice> result = new ArrayList<>();
result.add(new Notice("两部门向灾区预拨2亿元救灾资金"));
result.add(new Notice("特朗普被裁定不具备总统参选资格"));
result.add(new Notice("泰国瑞幸向中国瑞幸索赔20亿元"));
binding.layoutNotices.setVisibility(View.VISIBLE);
binding.noticesSwitcher.setInAnimation(R.anim.anim_notice_in).setOutAnimation(R.anim.anim_notice_out).bindData(result).startSwitch(2500);
完了,就这么简单