高级组件之图像切换器

1.使用imageswitcher创建图像切换器
布局代码:
<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="上一张" />

    <ImageSwitcher
        android:id="@+id/imageSwitcher1"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ImageSwitcher>

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下一张" />
2.声明并初始化一个保存要显示图像ID的数组
final int[] imageid = new int[]{R.drawable.img1,R.drawable.img2,
R.drawable.img3,R.drawable.img4,R.drawable.img5,
R.drawable.img6,R.drawable.img7,R.drawable.img8,
R.drawable.img9};
private int index = 0;
3.获取图像切换器并设置淡入淡出的动画效果
final ImageSwitcher imageSwitcher=(ImageSwitcher)findViewById(R.id.imageSwitcher1)
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
4.设置Factory,并重写make View()方法
imageSwitcher.setFactory(new ViewFactory() {

@Override
public View makeView() {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
return imageView;
}
});
imageSwitcher.setImageResource(imageid[index]);
5.为按钮添加监听事件
Button up = (Button)findViewById(R.id.button1);
Button down = (Button)findViewById(R.id.button2);
up.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (index>0) {
index--;
}else {
index=imageid.length-1;
}
imageSwitcher.setImageResource(imageid[index]);
}
});
down.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (index<imageid.length-1) {
index++;
}else {
index=0;
}
imageSwitcher.setImageResource(imageid[index]);
}
});

高级组件之图像切换器_第1张图片

你可能感兴趣的:(android)