本例介紹TextSwitcher 的用法,我們在前面介紹過ImageSwitcher的用法Android ApiDemos樣本解析(124):Views->ImageSwitcher ,ImageSwitcher 和TextViewSwitcher都是ViewSwitcher 的子類,ViewSwitcher又是ViewAnimator 的子類,ViewAnimator (FrameLayout的子類)提供了不同View之間切換時的動畫效果支援,而ViewAnimator 為FrameLayout的子類,因此ViewAnimator中包含的子View都是疊放在一起,一般情況下支援看到最上面的一個View。
ViewSwitcher只能最多包括兩個子View。每次只顯示其中一個View,它有兩個子類TextSwitcher 和ImageSwitcher 。本例介紹TextSwitcher ,TextSwitcher 種能包含TextView,TextSwitcher主要可以用法文字切換時動畫效果。
每當調用setText時,TextSwitcher 使用設定的動畫效果顯示新文字串和原先文字之間的切換。可以使用addView 為ViewSwitcher 手動添加一個View到ViewSwitcher中,也可以使用ViewSwitcher.ViewFactory 自動建立一個新View。本例使用ViewSwitcher.ViewFactory為TextSwitcher建立一個新View。在介紹TabControl 採用了類似的Factory方法Android ApiDemos樣本解析(194):Views->Tabs->Content By Factory。
[java]
public class TextSwitcher1 extends Activity
implements ViewSwitcher.ViewFactory,
View.OnClickListener {
private TextSwitcher mSwitcher;
private int mCounter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_switcher_1);
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
mSwitcher.setInAnimation(in);
mSwitcher.setOutAnimation(out);
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
public void onClick(View v) {
mCounter++;
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
}
public class TextSwitcher1 extends Activity
implements ViewSwitcher.ViewFactory,
View.OnClickListener {
private TextSwitcher mSwitcher;
private int mCounter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_switcher_1);
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
mSwitcher.setInAnimation(in);
mSwitcher.setOutAnimation(out);
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
public void onClick(View v) {
mCounter++;
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
}
為TextSwitcher 設定了淡入淡出的動畫效果來切換文字。