Android 循環上下滾動

最近在作項目的時候遇到了一個上下滾動文字的需求,在網上找到了一個自定義的TextView,可是切換效果很圖片,沒有滾動的效果,考慮到html的marquee效果添加到TextView中,無奈沒有效果,另外也瀏覽了js寫的滾動,效果很好,可是應用起來很麻煩,畢竟是Android原生界面。最後,只能本身作一個了(注:此處是兩句文字來回滾動)html

  • 1.佈局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fe0"
         >

        <TextView
            android:id="@+id/autoPlay"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="位移動畫"
            android:padding="16dp"/>
         <TextView
            android:id="@+id/autoPlay1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="位移動畫2"
            android:padding="16dp"/>
    </RelativeLayout>

</LinearLayout>

2.Activity中的代碼android

private TextView aView;
private TextView aView1;
final Handler handler = new Handler() {
		public void handleMessage(Message msg) { // handle message
			switch (msg.what) {
			case 1:
				// UI操做
                          //此處兩個TextView不分前後,只要與else裏的順序不一樣便可
				if (curIndex == 1) {
					autoPlay(aView, aView1);
					curIndex++;
				} else {
					autoPlay(aView1, aView);
					curIndex--;
				}

				Message message = handler.obtainMessage(1);
				//此處延時應大於等於動畫播放時間,不然會有卡頓現象
				// 發送message 
                                // 這樣消息就能循環發送
                              handler.sendMessageDelayed(message, 3000); 																		}
			super.handleMessage(msg);
		}
	};

在onCreate方法裏添加佈局

aView = (TextView) findViewById(R.id.autoPlay);
aView1 = (TextView) findViewById(R.id.autoPlay1);
Message message = handler.obtainMessage(1);
handler.sendMessageDelayed(message, 1000); // 發送message

3.autoPlay方法動畫

public void autoPlay(TextView aView, TextView aView1) {
		TranslateAnimation inAnimation = new TranslateAnimation(0, 0, 100, 0);
		inAnimation.setDuration(2000);
		inAnimation.setFillAfter(true);
		TranslateAnimation outAnimation = new TranslateAnimation(0, 0, 0, -100);
		outAnimation.setDuration(2000);
		outAnimation.setFillAfter(true);
		aView1.clearAnimation();
		aView.clearAnimation();
		aView1.startAnimation(outAnimation);
		aView.startAnimation(inAnimation);
	}
相關文章
相關標籤/搜索