ImageSwitcher,把她理解成一个相框的话,里面放的是一张张相片(ImageView对象),事实上,ImageSwitcher本身也是集成FrameLayout。
OK,直接上代码。
public class ImageSwitcherActivity extends Activity implements ViewFactory,OnClickListener{
/** Called when the activity is first created. */
private static final int BUTTON_DWON_ID=0x123456;
private static final int BUTTON_UP_ID=0x123457;
private static final int SWITCHER_ID=0x123458;
private int index=0;
private ImageSwitcher switcher;
int []images=new int[]{R.drawable.f,R.drawable.t,R.drawable.y};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
switcher =new ImageSwitcher(this);
//创建一个布局
LinearLayout layout=new LinearLayout(this);
setContentView(layout);
//加入组件
layout.addView(switcher);
switcher.setFactory(this);//设置工厂
switcher.setImageResource(images[index]);
//设置动画效果
switcher.setInAnimation(AnimationUtils.loadAnimation(this , android.R.anim.fade_in)) ;
switcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(100,100);
//创建下一张按钮
Button nextBt=new Button(this);
nextBt.setText("下一张");
nextBt.setId(BUTTON_DWON_ID);
nextBt.setOnClickListener(this);//创建监听
layout.addView(nextBt, params);
//创建上一张按钮
Button preBt=new Button(this);
preBt.setText("上一张");
preBt.setId(BUTTON_UP_ID);
preBt.setOnClickListener(this);//创建监听
layout.addView(preBt, params);
}
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(this);
imageView.setBackgroundColor(0xFF000000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return imageView;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case BUTTON_DWON_ID:
index++;
if(index>=images.length){
index=0;
}
switcher.setImageResource(images[index]);
break;
case BUTTON_UP_ID:
index--;
if(index<0){
index=images.length-1;
}
switcher.setImageResource(images[index]);
break;
default:
break;
}
}
}
简单解释下上述代码
要想让ImageSwitcher装载ImageView,就必须通过setFactory这个方法,并且重写ViewFactory的makeView方法