ImageSwitcher 是 Android 專門用來控制「圖片切換效果」的控件,最典型的就是幻燈片那種淡入淡出,拿來做相本剛剛好。它其實是 ViewSwitcher 的子類,同一時間只會顯示一個子 View,切換時靠進出動畫把舊的送走、新的接上。
setImageURI(Uri uri):直接指定圖片來源。
setImageResource(int resid):從資源庫載入,最常用。
setImageDrawable(Drawable drawable):使用自繪或加工過的 Drawable。
ImageSwitcher 不會自己產生要顯示的 View,必須先透過 setFactory(this) 提供一個 ViewFactory,實作 makeView() 回傳一個 ImageView。接著用 setInAnimation / setOutAnimation 指定進出動畫,最省事的做法是直接用系統內建的 android.R.anim.fade_in 與 fade_out。
is = (ImageSwitcher) findViewById(R.id.switcher); is.setFactory(this); is.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); is.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
常見的相本版型是上下分層:上半部放 ImageSwitcher 顯示大圖,下半部放一條半透明背景的 Gallery 當縮圖列。用 RelativeLayout 讓 ImageSwitcher 對齊父容器頂端、Gallery 對齊底端並固定高度(例如 60dp),Gallery 再設定 gravity 置中與 spacing 間距即可。
public class ImageSwitcherDemo extends Activity
implements OnItemSelectedListener, ViewFactory {
private ImageSwitcher is;
private Gallery gallery;
private Integer[] mImageIds = { R.drawable.b, R.drawable.c,
R.drawable.d, R.drawable.f, R.drawable.g };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.imageswitcherpage);
is = (ImageSwitcher) findViewById(R.id.switcher);
is.setFactory(this);
is.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
is.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemSelectedListener(this);
}
@Override
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return i;
}
@Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
is.setImageResource(mImageIds[position]);
}
@Override
public void onNothingSelected(AdapterView parent) { }
}
內部的 ImageAdapter 繼承 BaseAdapter,getCount 回傳縮圖數量,getView 建立 ImageView、設定縮圖資源、開啟 setAdjustViewBounds 讓比例不被扭曲,並用 Gallery.LayoutParams 設定寬高為 WRAP_CONTENT,再套一個自訂背景當作選中效果。
兩個實務提醒:makeView 回傳的 ImageView 一定要設定 LayoutParams,否則大圖會縮成一小塊;另外 ImageSwitcher 只保留兩個子 View 交替使用,所以每次換圖都是「重設同一批 ImageView 的資源」,不要自己在外部額外管理 ImageView 池。