1. 程式人生 > >橫向無限滾動TextView和豎向無限滾動TextView

橫向無限滾動TextView和豎向無限滾動TextView

一、橫向無限滾動TextView

1.自定義HorizontalTextView

public class HorizontalTextView extends android.support.v7.widget.AppCompatTextView implements View.OnClickListener {

    public final static String TAG = HorizontalTextView.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 HorizontalTextView(Context context) {
        super(context);
        initView();
    }

    public HorizontalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public HorizontalTextView(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;

        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state)
    {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState ss = (SavedState)state;
        super.onRestoreInstanceState(ss.getSuperState());

        step = ss.step;
        isStarting = ss.isStarting;

    }

    public static class SavedState extends BaseSavedState {
        public boolean isStarting = false;
        public float step = 0.0f;
        SavedState(Parcelable superState) {
            super(superState);
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeBooleanArray(new boolean[]{isStarting});
            out.writeFloat(step);
        }


        public static final Parcelable.Creator<SavedState> CREATOR
                = new Parcelable.Creator<SavedState>() {

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }
        };

        private SavedState(Parcel in) {
            super(in);
            boolean[] b = null;
            in.readBooleanArray(b);
            if(b != null && b.length > 0)
                isStarting = b[0];
            step = in.readFloat();
        }
    }


    public void startScroll()
    {
        isStarting = true;
        invalidate();
    }


    public void stopScroll()
    {
        isStarting = false;
        invalidate();
    }


    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawText(text, temp_view_plus_text_length - step, y, paint);
        if(!isStarting)
        {
            return;
        }
        step += 0.5;//0.5為文字滾動速度。
        if(step > temp_view_plus_two_text_length)
            step = textLength;
        invalidate();

    }

    @Override
    public void onClick(View v) {
        if(isStarting)
            stopScroll();
        else
            startScroll();
    }
}

2.佈局

<***.HorizontalTextView
        android:id="@+id/the_htv"
        android:layout_width="fill_parent"
        android:layout_height="30px"
        android:background="#EEE"
        android:inputType="text"
        android:textColor="#000"
        android:textSize="20px" />

注:*** 為包名

3.使用

theHtv.setText("你好呀");
theHtv.init(getActivity().getWindowManager());
theHtv.startScroll();

二、豎向無限滾動TextView

1.自定義VerticalTextView

public class VerticalTextView extends TextSwitcher implements ViewSwitcher.ViewFactory {

    private static final int FLAG_START_AUTO_SCROLL = 0;
    private static final int FLAG_STOP_AUTO_SCROLL = 1;
    private float mTextSize = 16;
    private int mPadding = 5;
    private int textColor = Color.BLACK;

    /**
     * @param textSize  字號
     * @param padding   內邊距
     * @param textColor 字型顏色
     */
    public void setText(float textSize, int padding, int textColor) {
        mTextSize = textSize;
        mPadding = padding;
        this.textColor = textColor;
    }

    private OnItemClickListener itemClickListener;
    private Context mContext;
    private int currentId = -1;
    private ArrayList<String> textList;
    private Handler handler;

    public VerticalTextView(Context context) {
        this(context, null);
        mContext = context;
    }

    public VerticalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        textList = new ArrayList<String>();
    }

    public void setAnimTime(long animDuration) {
        setFactory(this);
        Animation in = new TranslateAnimation(0, 0, animDuration, 0);
        in.setDuration(animDuration);
        in.setInterpolator(new AccelerateInterpolator());
        Animation out = new TranslateAnimation(0, 0, 0, -animDuration);
        out.setDuration(animDuration);
        out.setInterpolator(new AccelerateInterpolator());
        setInAnimation(in);
        setOutAnimation(out);
    }

    /**
     * 間隔時間
     *
     * @param time
     */
    public void setTextStillTime(final long time) {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case FLAG_START_AUTO_SCROLL:
                        if (textList.size() > 0) {
                            currentId++;
                            setText(textList.get(currentId % textList.size()));
                        }
                        handler.sendEmptyMessageDelayed(FLAG_START_AUTO_SCROLL, time);
                        break;
                    case FLAG_STOP_AUTO_SCROLL:
                        handler.removeMessages(FLAG_START_AUTO_SCROLL);
                        break;
                }
            }
        };
    }

    /**
     * 設定資料來源
     *
     * @param titles
     */
    public void setTextList(ArrayList<String> titles) {
        textList.clear();
        textList.addAll(titles);
        currentId = -1;
    }

    /**
     * 開始滾動
     */
    public void startAutoScroll() {
        handler.sendEmptyMessage(FLAG_START_AUTO_SCROLL);
    }

    /**
     * 停止滾動
     */
    public void stopAutoScroll() {
        handler.sendEmptyMessage(FLAG_STOP_AUTO_SCROLL);
    }

    @Override
    public View makeView() {
        TextView t = new TextView(mContext);
        t.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER);
        t.setMaxLines(1);
        t.setPadding(mPadding, mPadding, mPadding, mPadding);
        t.setTextColor(textColor);
        t.setTextSize(mTextSize);

        t.setClickable(true);
        t.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null && textList.size() > 0 && currentId != -1) {
                    itemClickListener.onItemClick(currentId % textList.size());
                }
            }
        });
        return t;
    }

    /**
     * 設定點選事件監聽
     *
     * @param itemClickListener
     */
    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    /**
     * 輪播文字點選監聽器
     */
    public interface OnItemClickListener {
        /**
         * 點選回撥
         *
         * @param position 當前點選ID
         */
        void onItemClick(int position);
    }
}

2.佈局

<***.VerticalTextView
        android:id="@+id/the_vtv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

注:*** 為包名

3.使用

資料來源

List<String> titleList = new ArrayList<>();

titleList .add("哈哈");
titleList .add("呵呵");
titleList .add("嘿嘿");

theVtv.setTextList(titleList);
theVtv.setText(14, 5, Color.RED);//設定屬性
theVtv.setTextStillTime(3000);//設定停留時長間隔
theVtv.setAnimTime(300);//設定進入和退出的時間間隔
theVtv.startAutoScroll();

停止滾動

@Override
    public void onDestroyView() {
        super.onDestroyView();
        theVtv.stopAutoScroll();
    }