转自: http://blog.sina.com.cn/s/blog_821e2bb10100uoao.html
标签: 杂谈 |
分类:Android学习 |
总结一下跑马灯的实现效果,网上比较流行的有两种,测试过了都可以实现文字滚动效果,建议使用第一种,因为可以更好地控制文字滚动速度、样式、字体等属性,第二种方法,还没有找到控制的方法!
第一种:
控件类:AutoScrollTextView继承了TextView并做了一些修改,实现了宽度的判断,文本自动滚动及开始和停止滚动等功能。
importandroid.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 implementsOnClickListener {
public finalstatic String TAG = AutoScrollTextView.class.getSimpleName();
privatefloat textLength = 0f;//文本长度
privatefloat viewWidth = 0f;
privatefloat step = 0f;//文字的横坐标
privatefloat y = 0f;//文字的纵坐标
privatefloat temp_view_plus_text_length = 0.0f;//用于计算的临时变量
privatefloat temp_view_plus_two_text_length = 0.0f;//用于计算的临时变量
publicboolean isStarting = false;//是否开始滚动
privatePaint paint = null;//绘图样式
privateString text = "";//文本内容
publicAutoScrollTextView(Context context) {
super(context);
initView();
}
public AutoScrollTextView(Context context, AttributeSet attrs){
super(context, attrs);
initView();
}
public AutoScrollTextView(Context context, AttributeSet attrs, intdefStyle) {
super(context, attrs, defStyle);
initView();
}
private voidinitView()
{
setOnClickListener(this);
}
public voidinit(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
publicParcelable onSaveInstanceState()
{
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.step = step;
ss.isStarting = isStarting;
return ss;
}
@Override
public voidonRestoreInstanceState(Parcelable state)
{
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
step = ss.step;
isStarting = ss.isStarting;
}
publicstatic 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 finalParcelable.Creator<SavedState>CREATOR
= newParcelable.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 voidstartScroll()
{
isStarting = true;
invalidate();
}
public voidstopScroll()
{
isStarting = false;
invalidate();
}
@Override
public voidonDraw(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 voidonClick(View v) {
if(isStarting)
stopScroll();
else
startScroll();
}
}
xml中使用方法:
<cn.tigertian.ui.AutoScrollTextView
android:id="@+id/TextViewNotice"
android:layout_height="30px"
android:layout_width="fill_parent"
android:text="@string/test_notice_1"
android:textColor="#000"
android:inputType="text"
android:background="#EEE"
android:textSize="20px">
</cn.tigertian.ui.AutoScrollTextView>
Activity中使用方法:
//启动公告滚动条
autoScrollTextView =(AutoScrollTextView)findViewById(R.id.TextViewNotice);
autoScrollTextView.init(getWindowManager());
autoScrollTextView.startScroll();
注:如果想改变跑马灯的文字内容或者文字效果,则在调用完setText方法之后,需要再调用一下init方法,重新进行初始化和相关参数的计算。
第二种:
publicclassAlwaysMarqueeTextViewextendsTextView{
publicAlwaysMarqueeTextView(Contextcontext){
super(context);
}
publicAlwaysMarqueeTextView(Contextcontext,AttributeSetattrs){
super(context,attrs);
}
publicAlwaysMarqueeTextView(Contextcontext,AttributeSetattrs,intdefStyle){
super(context,attrs,defStyle);
}
@Override
publicbooleanisFocused(){
returntrue;
}
在布局XML文件中加入这么一个AlwaysMarqueeTextView,这个加入方法也是刚刚学的。
ellipsize属性
设置当文字过长时,该控件该如何显示。有如下值设置:”start”—–省略号显示在开头;”end”——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee”——以跑马灯的方式显示(动画横向移动)
marqueeRepeatLimit属性
在ellipsize指定marquee的情况下,设置重复滚动的次数,当设置为marquee_forever时表示无限次。
focusable属性
自己猜测的,应该是能否获得焦点,同样focusableInTouchMode应该是滑动时能否获得焦点。
组合View的问题:
上面示例中2个TextView组合为一个View,由于设置了LinearLayout为focusable而TextView就没法取得焦点了,这样这个TextView的跑马灯效果就显示不出来,就算你也设置TextView的android:focusable=
"true"
也是没用的. 这个时候就要使用addStatesFromChildren这个属性了,在LinearLayout中设置这个属性,然后设置TextView的focusable=
"true"
就可以了.关于addStatesFromChildren的说明:
Sets whether
this
ViewGroup'sdrawable states
alsoinclude its children's drawable states.
///=================================================另一篇文章=========================================================
package com.firebear.android.sandbox.view;
import android.content.Context;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.animation.LinearInterpolator;
import android.widget.Scroller;
import android.widget.TextView;
public class ScrollTextView extends TextView {
// scrolling feature
private Scroller mSlr;
// milliseconds for a round of scrolling
private int mRndDuration = 250;
// the X offset when paused
private int mXPaused = 0;
// whether it's being paused
private boolean mPaused = true;
/*
* constructor
*/
public ScrollTextView(Context context) {
this(context, null);
}
/*
* constructor
*/
public ScrollTextView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
/*
* constructor
*/
public ScrollTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// customize the TextView
setSingleLine();
setEllipsize(null);
setVisibility(INVISIBLE);
}
/**
* begin to scroll the text from the original position
*/
public void startScroll() {
// begin from the very right side
mXPaused = -1 * getWidth();
// assume it's paused
mPaused = true;
resumeScroll();
}
/**
* resume the scroll from the pausing point
*/
public void resumeScroll() {
if (!mPaused)
return;
// Do not know why it would not scroll sometimes
// if setHorizontallyScrolling is called in constructor.
setHorizontallyScrolling(true);
// use LinearInterpolator for steady scrolling
mSlr = new Scroller(this.getContext(), new LinearInterpolator());
setScroller(mSlr);
int scrollingLen = calculateScrollingLen();
int distance = scrollingLen - (getWidth() + mXPaused);
int duration = (new Double(mRndDuration * distance * 1.00000
/ scrollingLen)).intValue();
setVisibility(VISIBLE);
mSlr.startScroll(mXPaused, 0, distance, 0, duration);
mPaused = false;
}
/**
* calculate the scrolling length of the text in pixel
*
* @return the scrolling length in pixels
*/
private int calculateScrollingLen() {
TextPaint tp = getPaint();
Rect rect = new Rect();
String strTxt = getText().toString();
tp.getTextBounds(strTxt, 0, strTxt.length(), rect);
int scrollingLen = rect.width() + getWidth();
rect = null;
return scrollingLen;
}
/**
* pause scrolling the text
*/
public void pauseScroll() {
if (null == mSlr)
return;
if (mPaused)
return;
mPaused = true;
// abortAnimation sets the current X to be the final X,
// and sets isFinished to be true
// so current position shall be saved
mXPaused = mSlr.getCurrX();
mSlr.abortAnimation();
}
@Override
/*
* override the computeScroll to restart scrolling when finished so as that
* the text is scrolled forever
*/
public void computeScroll() {
super.computeScroll();
if (null == mSlr) return;
if (mSlr.isFinished() && (!mPaused)) {
this.startScroll();
}
}
public int getRndDuration() {
return mRndDuration;
}
public void setRndDuration(int duration) {
this.mRndDuration = duration;
}
public boolean isPaused() {
return mPaused;
}
}