TextSwitcher实现滚动条广告(上下左右滚动)

TextSwitch实现滚动条广告的文章有不少,但不少滚动条广告都是只能上下滚动,因为需求问题,因此我在其余文章的基础上实现了当一条广告超出屏幕范围时进行向左滚动。java

先看效果(勉强看下~)android

接下来上代码app

简单布局页面activity_main.xmlide

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextSwitcher
        android:id="@+id/textSwitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="104dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

TextSwitch滚动动画实现——TextSwitcherAnimation.class布局

package com.example.myapplication;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.util.List;

public class TextSwitcherAnimation implements View.OnClickListener {

    private static final int DURATION = 1000;

    private TextSwitcher textSwitcher;
    private List<String> texts;
    private int marker;
    private AnimationSet InAnimationSet;
    private AnimationSet OutAnimationSet;

    private Context context;
    private String content;

    private int delayTime = 4000;
    private Handler handler = new Handler();
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            nextView();
            handler.postDelayed(task, delayTime * 2);

        }
    };

    public TextSwitcherAnimation(Context context,TextSwitcher textSwitcher, List<String> texts) {
        this.textSwitcher = textSwitcher;
        this.texts = texts;
        this.context = context;
    }

    public void start() {
        stop();
        handler.postDelayed(task, delayTime);
    }

    public void stop(){
        handler.removeCallbacks(task);
    }

    public int getMarker() {
        return marker;
    }

    public TextSwitcherAnimation setTexts(List<String> texts) {
        this.texts = texts;
        return this;
    }

    public void setDelayTime(int delayTime) {
        this.delayTime = delayTime;
    }

    public void create() {
        marker = 0;
        if (texts == null){
            Log.w("TextSwitcherAnimation", "texts is null");
            return;
        }
        if (textSwitcher == null) {
            Log.w("TextSwitcherAnimation", "textSwitcher is null");
            return;
        }
        textSwitcher.setText(texts.get(0));
        content = texts.get(0);
        createAnimation();
        textSwitcher.setInAnimation(InAnimationSet);
        textSwitcher.setOutAnimation(OutAnimationSet);
        textSwitcher.setOnClickListener(this);
        start();
    }

    private void createAnimation() {
        AlphaAnimation alphaAnimation;
        TranslateAnimation translateAnimation;

        int h = textSwitcher.getHeight();
        if (h <= 0) {
            textSwitcher.measure(0,0);
            h = textSwitcher.getMeasuredHeight();
        }

        InAnimationSet = new AnimationSet(true);
        OutAnimationSet = new AnimationSet(true);

        alphaAnimation = new AlphaAnimation(0,1);
        translateAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0,
                Animation.ABSOLUTE, h, Animation.ABSOLUTE, 0);
        InAnimationSet.addAnimation(alphaAnimation);
        InAnimationSet.addAnimation(translateAnimation);
        InAnimationSet.setDuration(DURATION);

        alphaAnimation = new AlphaAnimation(1,0);
        translateAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0,
                Animation.ABSOLUTE, 0, Animation.ABSOLUTE, -h);
        OutAnimationSet.addAnimation(alphaAnimation);
        OutAnimationSet.addAnimation(translateAnimation);
        OutAnimationSet.setDuration(DURATION);
    }

    private void nextView() {
        marker = ++marker % texts.size();
        content = texts.get(marker);
        textSwitcher.setText(texts.get(marker));
    }

    @Override
    public void onClick(View v) {
//        Toast.makeText(context,"内容:" +content+"\n位置:"+marker, Toast.LENGTH_SHORT).show();
    }
}

重点在于实现长广告的时候向左滚动post

textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                t = new TextView(MainActivity.this);
                t.setTextSize(15);
                t.setEllipsize(TextUtils.TruncateAt.MARQUEE);
                t.setTextColor(MainActivity.this.getResources().getColor(R.color.colorPrimary));
                t.setHorizontallyScrolling(true);//滚动必须添加
                t.setFocusableInTouchMode(true);
                t.setLines(1);
                t.setMarqueeRepeatLimit(-1);
                t.setFocusable(true);
                t.setSelected(true);
                return t;
            }
        });

完整MainActivity.class动画

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.List;

/**
 * first test
 */
public class MainActivity extends AppCompatActivity {

    /**
     * second test
     * 提交
     *
     * @param savedInstanceState
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTextSwitch();
        initTextView();

    }

    TextView textView;

    private void initTextView() {
        TextView textView = findViewById(R.id.textView2);
        textView.setText("111231564899741646465161651464444444465423848fa4fdagwgwgewggregre");
        textView.setHorizontallyScrolling(true);
        textView.setFocusableInTouchMode(true);
        textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        textView.setLines(1);
        textView.setMarqueeRepeatLimit(-1);
        textView.setFocusable(true);
        textView.setSelected(true);

    }

    TextView t;
    private TextSwitcherAnimation textSwitcherAnimation;

    private void initTextSwitch() {

        TextSwitcher textSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
        final List<String> texts = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
//            texts.add("循环....."+i);

            if(i==1||i==3){
                texts.add("第"+i+"条长广告asdfghjklqwertyuiopzxcvbnm!@#$%^&*()_+");
            }else {
                texts.add("第"+i+"条短广告");
            }
        }
        textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                t = new TextView(MainActivity.this);
                t.setTextSize(15);
                t.setEllipsize(TextUtils.TruncateAt.MARQUEE);
                t.setTextColor(MainActivity.this.getResources().getColor(R.color.colorPrimary));
                t.setHorizontallyScrolling(true);//滚动必须添加
                t.setFocusableInTouchMode(true);
                t.setLines(1);
                t.setMarqueeRepeatLimit(-1);
                t.setFocusable(true);
                t.setSelected(true);
                return t;
            }
        });

//        new TextSwitcherAnimation(MainActivity.this,textSwitcher,texts).create();
        if (textSwitcher.getCurrentView() == null) {
            textSwitcherAnimation = new TextSwitcherAnimation(MainActivity.this, textSwitcher, texts);
            textSwitcherAnimation.create();
            textSwitcher.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int mark = textSwitcherAnimation.getMarker();
                    Toast.makeText(MainActivity.this, "new内容:" + texts.get(mark) + "\n位置:" + mark + "", Toast.LENGTH_SHORT).show();
                }
            });

        }
        if (textSwitcherAnimation == null) {
            textSwitcherAnimation = new TextSwitcherAnimation(this, textSwitcher, texts);
            textSwitcherAnimation.create();
            textSwitcher.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int mark = textSwitcherAnimation.getMarker();
                    Toast.makeText(MainActivity.this, "new内容:" + texts.get(mark) + "\n位置:" + mark + "", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            if (texts != null) {
                textSwitcherAnimation.setTexts(texts);
                if (texts.size() <= 1) {
                    textSwitcherAnimation.stop();
                    textSwitcherAnimation.create();
                    textSwitcher.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int mark = textSwitcherAnimation.getMarker();
                            Toast.makeText(MainActivity.this, "new内容:" + texts.get(mark) + "\n位置:" + mark + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    textSwitcherAnimation.start();
                    textSwitcherAnimation.create();
                    textSwitcher.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int mark = textSwitcherAnimation.getMarker();
                            Toast.makeText(MainActivity.this, "new内容:" + texts.get(mark) + "\n位置:" + mark + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }

    }
}

完成,因为只是我的简单Demo的书写,因此并非很规范,能够根据本身需求去规范代码。ui