小言_互联网的博客

Android UI学习之NoticeView实现文字轮播效果

230人阅读  评论(0)

今天搬砖赚了500,你以为我要给你450,然后留50吃泡面。
不!!! 你格局小了!!!
我会再向朋友再借20凑520给你。

—广州 · 14℃ · 阴天 · 天暗下来,你就是阳光~

效果展示

如何实现?

首先感谢一下编写NoticeView控件的作者,GitHub传送门:https://github.com/czy1121/noticeview ,喜欢的朋友可以为他点下star。

为了方便大家使用,在下面贴出控件源码,直接复制过去就可以使用:

  • NoticeView控件的属性,在res/values文件下定义一个attrs.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="NoticeView">
        <!-- 图标 -->
        <attr name="nvIcon" format="reference"/>
        <!-- 图标与内容的间隙 -->
        <attr name="nvIconPadding" format="dimension"/>
        <!-- 图标颜色 -->
        <attr name="nvIconTint" format="color"/>

        <!-- 文本尺寸 -->
        <attr name="nvTextSize" format="dimension"/>
        <!-- 文本颜色 -->
        <attr name="nvTextColor" format="color"/>
        <!-- 文本最大行数 -->
        <attr name="nvTextMaxLines" format="integer"/>
        <!-- 文本对齐方式 -->
        <attr name="nvTextGravity" format="integer">
            <enum name="left" value="3"/>
            <enum name="center" value="17"/>
            <enum name="right" value="5"/>
        </attr>

        <!-- 切换动画间隔时间,毫秒 -->
        <attr name="nvInterval" format="integer"/>
        <!-- 切换动画持续时间,毫秒 -->
        <attr name="nvDuration" format="integer"/>
    </declare-styleable>


</resources>
  • NoticeView源码:
public class NoticeView extends TextSwitcher {
   

    private Animation mInUp = anim(1.5f, 0);
    private Animation mOutUp = anim(0, -1.5f);

    private List<String> mDataList = new ArrayList<>();

    private int mIndex = 0;
    private int mInterval = 4000;
    private int mDuration = 900;

    private Drawable mIcon;
    private int mIconTint = 0xff999999;
    private int mIconPadding = 0;
    private int mPaddingLeft = 0;

    private boolean mIsVisible = false;
    private boolean mIsStarted = false;
    private boolean mIsResumed = true;
    private boolean mIsRunning = false;
    private final TextFactory mDefaultFactory = new TextFactory();
    private final Runnable mRunnable = new Runnable() {
   
        @Override
        public void run() {
   
            if (mIsRunning) {
   
                show(mIndex + 1);
                postDelayed(mRunnable, mInterval);
            }
        }
    };

    public NoticeView(Context context) {
   
        this(context, null);
    }

    public NoticeView(Context context, AttributeSet attrs) {
   
        super(context, attrs);
        initWithContext(context, attrs);
        setInAnimation(mInUp);
        setOutAnimation(mOutUp);
        setFactory(mDefaultFactory);
        mInUp.setDuration(mDuration);
        mOutUp.setDuration(mDuration);
    }

    private void initWithContext(Context context, AttributeSet attrs) {
   
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NoticeView);
        mIcon = a.getDrawable(R.styleable.NoticeView_nvIcon);
        mIconPadding = (int)a.getDimension(R.styleable.NoticeView_nvIconPadding, 0);

        boolean hasIconTint = a.hasValue(R.styleable.NoticeView_nvIconTint);

        if (hasIconTint) {
   
            mIconTint = a.getColor(R.styleable.NoticeView_nvIconTint, 0xff999999);
        }

        mInterval = a.getInteger(R.styleable.NoticeView_nvInterval, 4000);
        mDuration = a.getInteger(R.styleable.NoticeView_nvDuration, 900);

        mDefaultFactory.resolve(a);
        a.recycle();

        if (mIcon != null) {
   
            mPaddingLeft = getPaddingLeft();
            int realPaddingLeft = mPaddingLeft + mIconPadding + mIcon.getIntrinsicWidth();
            setPadding(realPaddingLeft, getPaddingTop(), getPaddingRight(), getPaddingBottom());

            if (hasIconTint) {
   
                mIcon = mIcon.mutate();
                DrawableCompat.setTint(mIcon, mIconTint);
            }
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mIcon != null) {
   
            int y = (getMeasuredHeight() - mIcon.getIntrinsicWidth()) / 2;
            mIcon.setBounds(mPaddingLeft, y, mPaddingLeft + mIcon.getIntrinsicWidth(), y + mIcon.getIntrinsicHeight());
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
   
        super.onDraw(canvas);
        if (mIcon != null) {
   
            mIcon.draw(canvas);
        }
    }

    public int getIndex() {
   
        return mIndex;
    }

    public void start(List<String> list) {
   
        mDataList = list;
        if (mDataList == null || mDataList.size() < 1) {
   
            mIsStarted = false;
            update();
        } else {
   
            mIsStarted = true;
            update();
            show(0);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
   
        super.onDetachedFromWindow();
        mIsVisible = false;
        update();
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
   
        super.onWindowVisibilityChanged(visibility);
        mIsVisible = visibility == VISIBLE;
        update();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
   
        int action = ev.getAction();
        switch (action) {
   
        case MotionEvent.ACTION_DOWN:
            mIsResumed = false;
            update();
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            mIsResumed = true;
            update();
            break;

        }
        return super.dispatchTouchEvent(ev);
    }

    private void update() {
   
        boolean running = mIsVisible && mIsResumed && mIsStarted;
        if (running != mIsRunning) {
   
            if (running) {
   
                postDelayed(mRunnable, mInterval);
            } else {
   
                removeCallbacks(mRunnable);
            }
            mIsRunning = running;
        }
        Log.e("ezy", "update() visible=" + mIsVisible + ", started=" + mIsStarted + ", running=" + mIsRunning);
    }

    private void show(int index) {
   
        mIndex = index % mDataList.size();
        setText(Html.fromHtml(mDataList.get(mIndex)));
    }

    private Animation anim(float from, float to) {
   
        final TranslateAnimation anim = new TranslateAnimation(0, 0f, 0, 0f, Animation.RELATIVE_TO_PARENT, from, Animation.RELATIVE_TO_PARENT, to);
        anim.setDuration(mDuration);
        anim.setFillAfter(false);
        anim.setInterpolator(new LinearInterpolator());
        return anim;
    }

    class TextFactory implements ViewFactory {
   
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();

        float size = dp2px(14);
        int color = 1;
        int lines = 1;
        int gravity = Gravity.LEFT;

        void resolve(TypedArray ta) {
   
            lines = ta.getInteger(R.styleable.NoticeView_nvTextMaxLines, lines);
            size = ta.getDimension(R.styleable.NoticeView_nvTextSize, size);
            color = ta.getColor(R.styleable.NoticeView_nvTextColor, color);
            gravity = ta.getInteger(R.styleable.NoticeView_nvTextGravity, gravity);
        }

        private int dp2px(float dp) {
   
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm);
        }
        @Override
        public View makeView() {
   
            TextView tv = new TextView(getContext());
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
            tv.setMaxLines(lines);
            if (color != 1) {
   
                tv.setTextColor(color);
            }
            tv.setEllipsize(TextUtils.TruncateAt.END);
            tv.setGravity(Gravity.CENTER_VERTICAL | gravity);
            tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            return tv;
        }
    }
}

使用起来非常简单:


        final String[] test = new String[]{
   
                "须知少时凌云志,",
                "曾许人间第一流。",
                "哪晓岁月蹉跎过,",
                "依然名利两无收。"
        };
        noticeView = findViewById(R.id.nv_notice);
        noticeView.start(Arrays.asList(test));
        noticeView.setOnClickListener(new View.OnClickListener() {
   
            @Override
            public void onClick(View v) {
   
                // TODO: 2021/3/21  
                Toast.makeText(XXActivity.this, test[noticeView.getIndex()], Toast.LENGTH_SHORT).show();
            }
        });
        

但是需要注意一点,如果没给NoticeView设置setOnClickListener点击事件,那么当NoticeView在轮播时被点击后会出现暂停现象,并且它也不会自动恢复轮播,无论再怎么点击NoticeView,它都会一直处于停止状态
如果NoticeView只是用于显示信息轮播,不需要监听其点击事件,那可以在NoticeView里面将dispatchTouchEvent()删掉就好了。

非常感谢你能看到这里,如果能够帮助到你是我的荣幸!


转载:https://blog.csdn.net/qq_36270361/article/details/115048571
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场