How to animate the textview (very very long text )scroll automatically horizontally

前端 未结 11 932
长发绾君心
长发绾君心 2020-12-16 06:30

I am not interested in Marquee because, in Marquee you can not control the speed of marquee. I have tried to animate the textview but Parent view clips the text at the end e

11条回答
  •  情歌与酒
    2020-12-16 07:08

    Can try out this. This is a solution using TranslateAnimation for creating an auto scrolling text (horizontal scroll, from Right to Left) (Tested on Android 8)

    Class: AnimationAutoTextScroller.java

    /**
     * A Class for automatically scrolling text horizontally from Right to Left 
     * using TranslateAnimation so that the scrolling speed can be controlled -Suresh Kodoor
     */
    
    public class AnimationAutoTextScroller {
    
        Animation animator;
        TextView  scrollingTextView;
        int       duration = 50000;  // default value
    
        public AnimationAutoTextScroller(TextView tv, float screenwidth) {
    
            this.scrollingTextView = tv;
            this.animator = new TranslateAnimation(
                    Animation.ABSOLUTE, screenwidth,
                    Animation.RELATIVE_TO_SELF, -1f,
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f
            );
            this.animator.setInterpolator(new LinearInterpolator());
            this.animator.setDuration(this.duration);
            this.animator.setFillAfter(true);
            this.animator.setRepeatMode(Animation.RESTART);
            this.animator.setRepeatCount(Animation.INFINITE);
    
            // setAnimationListener();
        }
    
        public void setDuration(int duration) {
            this.duration = duration;
        }
    
        public void setScrollingText(String text) {
            this.scrollingTextView.setText(text);
        }
    
        public void start() {
            this.scrollingTextView.setSelected(true);
            this.scrollingTextView.startAnimation(this.animator);
        }
    
        public void setAnimationListener() {
    
            animator.setAnimationListener(new Animation.AnimationListener() {
                public void onAnimationStart(Animation animation) {
                }
                public void onAnimationEnd(Animation animation) {
                    // This callback function can be used to perform any task at the end of the Animation
                }
                public void onAnimationRepeat(Animation animation) {
                }
            });
        }
    }
    

    Layout XML: (keep the TextView under a HorizontalScrollView)

     
    
        
    
          
    

    Activity:

    TextView scrollertextview = findViewById(R.id.translateanimatortextviewscroller);
    textscroller = new AnimationAutoTextScroller(scrollertextview, screenwidth);
    textscroller.setScrollingText(scrollertext);
    textscroller.setDuration(60000);
    textscroller.start();
    

提交回复
热议问题