<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
package com.example.imageswitcherdemo;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class MainActivity extends Activity {
private ImageSwitcher mySwitch=null;
private Button previous=null;
private Button next=null;
private int foot=0;
//存放图片的地方
private int[] imgRes=new int[]{
R.drawable.ispic_a,R.drawable.ispic_b,R.drawable.ispic_c,R.drawable.ispic_d,R.drawable.ispic_e
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mySwitch=(ImageSwitcher) super.findViewById(R.id.myImageSwitch);
this.previous=(Button) super.findViewById(R.id.previous);
this.next=(Button) super.findViewById(R.id.next);
//为我们的上一张按钮添加方法
this.previous.setOnClickListener(new OnPreButClickListenerImp());
//为我们的下一张添加方法
this.next.setOnClickListener(new OnNextButClickListenerImp());
//如果不设置转换工厂,会出错。
this.mySwitch.setFactory(new ViewFactoryImp());
this.mySwitch.setImageResource(this.imgRes[this.foot]);
//添加动画效果
this.mySwitch.setInAnimation(AnimationUtils.loadAnimation
(
this,
android.R.anim.fade_in //进入时候的效果
));
this.mySwitch.setOutAnimation( AnimationUtils.loadAnimation
(
this,
android.R.anim.fade_out
));
}
//上一张
public class OnPreButClickListenerImp implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
if(MainActivity.this.foot!=0){
MainActivity.this.mySwitch.setImageResource(MainActivity.this.imgRes[--MainActivity.this.foot]);
}
else{
Toast.makeText(MainActivity.this, "已经是第一张", Toast.LENGTH_SHORT).show();
}
}
}
//下一张
public class OnNextButClickListenerImp implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
if(MainActivity.this.foot!=MainActivity.this.imgRes.length-1){
MainActivity.this.mySwitch.setImageResource(MainActivity.this.imgRes[++MainActivity.this.foot]);
}
else{
Toast.makeText(MainActivity.this, "已经是最后一张", Toast.LENGTH_SHORT).show();
}
}
}
private class ViewFactoryImp implements ViewFactory{
public View makeView() {
ImageView img=new ImageView(MainActivity.this);
//设置背景
img.setBackgroundColor(0xFFFFFF);
//按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分显示
img.setScaleType(ImageView.ScaleType.CENTER);
img.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT
));
return img;
}
}
}