TextSwitcher元件應用

文字的切換動畫也是有一個叫TextSwitcher 的類別可以做到,它的使用方法和
ImageSwitcher 類似。

1. hellotextswitcher.xml 中添加一個TextSwitcher 元件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextSwitcher
        android:id="@+id/textSwitcher1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TextSwitcher>

</LinearLayout>

2.新增 HelloTextSwitcher.java

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

public class HelloTextSwitcher extends Activity {
// 索引
private int index;
// 文字陣列
private String[] poemArray = { "床前明月光", "疑似地上霜", "舉頭望明月", "低頭思故鄉" };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hellotextswitcher);
// 定義文字切換器
final TextSwitcher ts = (TextSwitcher) findViewById(R.id.textSwitcher1);
// 定義視圖顯示工廠
ts.setFactory(new ViewFactory() {
@Override
public View makeView() {
TextView tv = new TextView(HelloTextSwitcher.this);
tv.setTextSize(32);
tv.setTextColor(Color.GREEN);
return tv;
}
});
// 設置文字來源
ts.setText(poemArray[index]);
// 設置點擊監聽器
ts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 點擊會切換文字
index++;
if (index >= poemArray.length) {
index = 0;
}
ts.setText(poemArray[index]);
}
});
// 設定切入動畫
ts.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
android.R.anim.slide_in_left));
// 設定切出動畫
ts.setOutAnimation(AnimationUtils.loadAnimation(
getApplicationContext(), android.R.anim.slide_out_right));
}
}

沒有留言: