一、Gallery的使用
(Gallery是過期控件,以後不建議使用,可用HorizontalScrollView、ImageView代替)
1. 在佈局xml文件中添加Gallery標籤
<Gallery
android:id="@+id/gallery"
....
/>
2.準備數據源
<span style="font-size:18px;">int[] res={R.drawable.item1,R.drawable.item2,...};</span>
3.可以自定義一個數據適配器如ImageAdapter (繼承BaseAdapter)
(1)BaseAdapter中的重要方法
public int getCount()//返回已定義的數據源的總數量
{
return res.length; //Gallery循環滾動功能時,改爲 return Integer.MAX_VALUE;
}
public Object getItem(int position)//取得當前容器中的對象
public long getItemId(int position)//取得當前容器中的數據ID,即數組下標的值
public View getView(int position, View convertView, ViewGroup parent)//取得目前欲顯示的圖像View,傳入數組ID值使之讀取與成像。根據數據源的個數,會調用相應次數的getView方法
{
ImageView image=new ImageView(context);
image.setBackGroundResource(res[position]);//Gallery循環滾動功能時,改爲res[position%res.length];
image.setLayoutParams(new Gallery.LayoutParams(200,150));//圖片在Gallery中的大小
image.setScaleType(ScaleType.FIT_XY);//橫向縱向的拉伸到200*150
return image;
}
ImageAdapter需要一個構造函數
ImageAdapter(int[] res, Context context)
4.加載適配器
adapter=new ImageAdapter(res,this);
gallery.setAdapter(adapter);
5. Gallery的監聽器OnItemSelectedListener
gallery加載監聽器 gallery.setOnItemSelectedListener(this);
監聽器包含兩個函數 onItemSelected (傳入當前選中的圖片,及其位置position)和 onNothingSelected
二、ImageSwitcher的使用(與ImageView功能類似,但是效果更炫,可指定圖片切換時的動畫效果)
1.在佈局xml文件中添加ImageSwitcher標籤
<ImageSwitcher
android:id="@+id/is"
......></ImageSwitcher>
2. 爲了讓ImageSwitcher對象 is加載圖片,需讓is所在的當前類實現接口 ViewFactory,重寫其View makeView()方法
public View makeView(){
ImageView image=new ImageView(this);
image.setScaleType(ScaleType.FIT_CENTER);//等比例縮放,保持圖片居中
return image;
}
3. ImageSwitcher加載圖片資源(實驗中在Gallery監聽事件方法onItemSelected中實現)
is.setBackgroundResource(res[position%res.length]);
4. ImageSwitcher對象加載Factory —— is.setFactory(this);
5. ImageSwitcher設置動畫效果
is.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in);//淡入
is.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out);//淡出