android 实现循环播放的文字跑马灯效果

 今天因为项目需要实现一个文字跑马灯的效果,作为进门不久我也不知道怎么办,就在网上搜了一下,受前辈们的启发,我实现了一个简单的循环播放文字的跑马灯效果。

首先,自定义一个让其继承TextView并实现Runnable接口。

public class MarqueeTextView extends TextView implements Runnable{

	private int currentScrollX;//当前滚动的位置
	private boolean isStop=false;
	private int textWidth;
	private boolean isMeasure=false;
	public MarqueeText(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	public MarqueeText(Context context,AttributeSet attrs) {
		super(context,attrs);
		// TODO Auto-generated constructor stub
	}
	public MarqueeText(Context context,AttributeSet attrs,int defStyle) {
		super(context,attrs,defStyle);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		if (!isMeasure) {//文字宽度只需要获取一次就可以了
			getTextWidth();
			isMeasure=true;
		}
	}
	/**
	 * 获取文字宽度 
	 */
	private void getTextWidth(){
		Paint paint=this.getPaint();
		String str=this.getText().toString();
		textWidth=(int) paint.measureText(str);
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		currentScrollX-=2;  // Rolling speed
		scrollTo(currentScrollX, 0);
		if (isStop) {
			return;
		}
		if (getScaleX()<=-(this.getWidth())) {
			scrollTo(textWidth, 0);
			currentScrollX=textWidth;
			//return;
		}
		postDelayed(this, 5);
	}
	// start
	public void startScroll(){
		isStop=false;
		this.removeCallbacks(this);
		post(this);
	}
	// stop
	public void stopScroll(){
		isStop=true;
	}
	// Start from scratch
	public void startFor0(){
		currentScrollX=0;
		startScroll();
	}
其次,在布局文件在一定要写上 android:ellipsize="marquee"
           android:focusable="true"
             android:focusableInTouchMode="true"

 android:marqueeRepeatLimit="marquee_forever"(实现无限循环)

main_activity.xml



    

        
        

        
最后,在MainActivity.java 中去实现它

public class MainActivity extends Activity {
	
	private MarqueeText text;
	private LinearLayout layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		text = (MarqueeText) findViewById(R.id.test);
		layout = (LinearLayout) findViewById(R.id.my_layout);
	}


	public void stop(View v) {
		text.stopScroll();
		layout.setVisibility(View.GONE);
	}

}





你可能感兴趣的:(Android)