TextSwitcher实现公告向上轮播动画




    

    






import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.thomas.android.base.R;

public class TextSwitcherActivity extends AppCompatActivity {

    private TextSwitcher text_switcher;
    private CharSequence[] text = new CharSequence[]{
            "小主人在萨摩耶面前耍小脾气,萨摩耶的举动,让人大呼不可能",
            "平面设计师经常去哪些网站?","减肥先改掉这3个恶习," +
            "花2分钟看完,易胖体质也能减肥"
    };
    private int index;
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_switcher);
        text_switcher = findViewById(R.id.text_switcher);
        initSwitcher();
    }

    private void initSwitcher() {
        text_switcher.setFactory(new TextFactory());
        text_switcher.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.toast_anim_in));
        text_switcher.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.toast_anim_out));
        index = 0;
        text_switcher.setText(text[index]);
        new Thread(textRunnable).start();

    }

    private Runnable textRunnable = new Runnable() {
        @Override
        public void run() {
            index++;
            if (index >= text.length){
                index = 0;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    text_switcher.setText(text[index]);
                }
            });

            handler.postDelayed(this,3000);
        }
    };

    private class TextFactory implements ViewSwitcher.ViewFactory{

        @Override
        public View makeView() {
            TextView textView = new TextView(TextSwitcherActivity.this);
            textView.setLayoutParams(new TextSwitcher.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            textView.setTextSize(25);
            textView.setMaxLines(1);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            return textView;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}

TextSwitcher实现公告向上轮播动画_第1张图片

你可能感兴趣的:(TextSwitcher实现公告向上轮播动画)