xml代码 :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ViewFlipper android:id="@+id/viewFilpper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"></ViewFlipper>
</RelativeLayout>
新建anim,里面定义两个动画文件
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0"
android:toXDelta="300"
android:duration="2000"/>
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-300"
android:toXDelta="0"
android:duration="2000"/>
</set>
java代码
package com.example.aoe;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class MainActivity extends Activity {
private ViewFlipper flipper;
final int FLAG_MSG=0x001;
private Message message;
private Animation[] animation=new Animation[2];
int[] images=new int[]{R.drawable.app_icon,R.drawable.banner_1,R.drawable.banner_2};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flipper=(ViewFlipper)findViewById(R.id.viewFilpper);
for(int i=0;i<images.length;i++){
ImageView imageView=new ImageView(this);
imageView.setImageResource(images[i]);
flipper.addView(imageView);
}
animation[0]=AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
animation[1]=AnimationUtils.loadAnimation(this, R.anim.slide_out_left);
flipper.setInAnimation(animation[0]);
flipper.setOutAnimation(animation[1]);
message=Message.obtain(); //获取Message对象
message.what=FLAG_MSG; //设置消息代码
handler.sendMessage(message); //发送消息
}
Handler handler=new Handler(){
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==FLAG_MSG){
flipper.showPrevious(); //切换到下一张图片
message=handler.obtainMessage(FLAG_MSG); //获取Message
handler.sendMessageDelayed(message, 3000); //延迟3秒发送
}
};
};
};