您的位置:首页 > 移动开发 > Android开发

Android 文字自动滚动(跑马灯)效果的两种实现方法

2012-01-11 21:40 1011 查看
总结一下跑马灯的实现效果,网上比较流行的有两种,测试过了都可以实现文字滚动效果,建议使用第一种,因为可以更好地控制文字滚动速度、样式、字体等属性,第二种方法,还没有找到控制的方法!

 

 

第一种:

控件类:AutoScrollTextView 继承了TextView并做了一些修改,实现了宽度的判断,文本自动滚动及开始和停止滚动等功能。

 

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.os.Parcel;

import android.os.Parcelable;

import android.util.AttributeSet;

import android.view.Display;

import android.view.View;

import android.view.WindowManager;

import android.view.View.OnClickListener;

import android.widget.TextView;

public class AutoScrollTextView extends TextView implements OnClickListener {

    public final static String TAG = AutoScrollTextView.class.getSimpleName();

   

    private float textLength = 0f;//文本长度

    private float viewWidth = 0f;

    private float step = 0f;//文字的横坐标

    private float y = 0f;//文字的纵坐标

    private float temp_view_plus_text_length = 0.0f;//用于计算的临时变量

    private float temp_view_plus_two_text_length = 0.0f;//用于计算的临时变量

    public boolean isStarting = false;//是否开始滚动

    private Paint paint = null;//绘图样式

    private String text = "";//文本内容

   

    public AutoScrollTextView(Context context) {

        super(context);

        initView();

    }

    public AutoScrollTextView(Context context, AttributeSet attrs) {

        super(context, attrs);

        initView();

    }

    public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);

        initView();

    }

   

   

    private void initView()

    {

        setOnClickListener(this);

    }

   

   

    public void init(WindowManager windowManager)

    {

        paint = getPaint();

        text = getText().toString();

        textLength = paint.measureText(text);

        viewWidth = getWidth();

        if(viewWidth == 0)

        {

            if(windowManager != null)

            {

                Display display = windowManager.getDefaultDisplay();

                viewWidth = display.getWidth();

            }

        }

        step = textLength;

        temp_view_plus_text_length = viewWidth + textLength;

        temp_view_plus_two_text_length = viewWidth + textLength * 2;

        y = getTextSize() + getPaddingTop();

    }

   

    @Override

    public Parcelable onSaveInstanceState()

    {

        Parcelable superState = super.onSaveInstanceState();

        SavedState ss = new SavedState(superState);

       

        ss.step = step;

        ss.isStarting = isStarting;

       

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息