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

TextSwitch实现滚动条广告的文章有很多,但很多滚动条广告都是只能上下滚动,由于需求问题,所以我在其他文章的基础上实现了当一条广告超出屏幕范围时进行向左滚动。

先看效果(勉强看下~)

接下来上代码

简单布局页面activity_main.xml

<?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();
    }
}

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

 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的书写,所以并不是很规范,可以根据自己需求去规范代码。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在最新版的Android Studio中实现TextSwitcher的上下滚动效果,可以按照以下步骤进行操作: 1. 在XML布局文件中,将TextSwitcher添加到你的布局中: ```xml <TextSwitcher android:id="@+id/textSwitcher" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inAnimation="@android:anim/slide_in_bottom" android:outAnimation="@android:anim/slide_out_top" /> ``` 2. 在Java代码中,获取TextSwitcher的实例并设置相应的属性和动画: ```java TextSwitcher textSwitcher = findViewById(R.id.textSwitcher); // 设置TextSwitcher的文本切换动画 textSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left)); textSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right)); // 设置TextSwitcher的文本颜色、字体大小等属性 textSwitcher.setTextColor(Color.BLACK); textSwitcher.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); ``` 3. 添加要显示的文本到TextSwitcher中,并设置相应的点击事件监听器: ```java textSwitcher.setText("First Text"); textSwitcher.setOnClickListener(new View.OnClickListener() { int counter = 0; @Override public void onClick(View v) { counter++; if (counter % 2 == 0) { textSwitcher.setText("First Text"); } else { textSwitcher.setText("Second Text"); } } }); ``` 这样,当你点击TextSwitcher时,它将在 "First Text" 和 "Second Text" 之间进行切换,并且会显示滑入和滑出的动画效果。你可以根据自己的需求修改文本和动画样式。希望这能帮到你!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值