首先需写一个自定义控件,NoticeView
public class NoticeView extends ViewFlipper implements View.OnClickListener { private Context mContext; private List<String> mNotices; private OnNoticeClickListener mOnNoticeClickListener; public NoticeView(Context context) { super(context); } public NoticeView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { mContext = context; //轮播间隔时间3s setFlipInterval(3000); // // 内边距5dp // setPadding(dp2px(5f), dp2px(5f), dp2px(5f), dp2px(5f)); //设置动画 setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.anim_marquee_in)); setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.anim_marquee_out)); } public void addNotice(List<String> notices) { mNotices = notices; removeAllViews(); for (int i = 0; i < mNotices.size(); i++) { // 根据公告内容构建一个TextView String notice = notices.get(i); TextView textView = new TextView(mContext); textView.setSingleLine(); textView.setText(notice); textView.setTextSize(13f); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setTextColor(Color.parseColor("#666666")); textView.setGravity(Gravity.CENTER_VERTICAL); // 将公告的位置设置为textView的tag方便点击是回调给用户 textView.setTag(i); textView.setOnClickListener(this); //添加到ViewPlipper NoticeView.this.addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } } @Override public void onClick(View v) { int position = (int) v.getTag(); String notice = mNotices.get(position); if (mOnNoticeClickListener != null) { mOnNoticeClickListener.onNoticeClick(position, notice); } } /** * 通知点击监听接口 */ public interface OnNoticeClickListener { void onNoticeClick(int position, String notice); } /** * 设置通知点击监听器 * * @param onNoticeClickListener 通知点击监听器 */ public void setmOnNoticeClickListener(OnNoticeClickListener onNoticeClickListener) { mOnNoticeClickListener = onNoticeClickListener; } private int dp2px(float dpValue) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, mContext.getResources().getDisplayMetrics()); } }然后在xml布局文件中引用自定义控件
<cn.app.activity.sub.NoticeView android:id="@+id/notice_view_home" android:layout_width="wrap_content" android:layout_height="wrap_content" />在Activity中
private NoticeView noticeView; noticeView = view.findViewById(R.id.notice_view_home); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //定义一个数组,接收后台传的数据 ArrayList<String> content1 = new ArrayList<>(); //添加到Notice noticeView.addNotice(content1); //开始运行 noticeView.startFlipping();这样就可以轮播数组里面的item啦,过段时间会上传Github,需要源代码的等我这段时间忙完会给链接下载的