图片的切换可以使用ImageSwitcher来实现,同样文本的切换动画也可以使用Android TextSwitcher类,他们都继承ViewSwitcher类。
ViewSwitcher仅仅包含子类型TextView。TextSwitcher被用来使屏幕上的label产生动画效果。每当setText(CharSequence)被调用时,TextSwitcher使用动画方式将当前的文字内容消失并显示新的文字内容。
package com.android.study;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
public class TextSwitcherActivity extends Activity implements ViewFactory {
/** Called when the activity is first created. */
TextSwitcher switcher;
Handler handler;
String[] resources = { " ", "身是菩提树,", "心如明镜台,", "时时勤拂拭,", "勿使惹尘埃。" };
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
id = next(); // 更新Id值
updateText(); // 更新TextSwitcherd显示内容;
break;
}
};
};
int id = 0; // resources 数组的Id;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTask(), 1, 3000);// 每3秒更新
}
private void init() {
switcher = (TextSwitcher) findViewById(R.id.switcher);
switcher.setFactory(this);
switcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
}
private int next() {
int flag = id + 1;
if (flag > resources.length - 1) {
flag = flag - resources.length;
}
return flag;
}
private void updateText() {
switcher.setText(resources[id]);
}
@Override
public View makeView() {
// TODO Auto-generated method stub
TextView tv = new TextView(this);
tv.setText(resources[id]);
return tv;
}
private class MyTask extends TimerTask {
@Override
public void run() {
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
}
}