Step 1:准備圖片素材.
將icon2,icon3,icon4,icon5,icon6五張圖片導入res/drawable裡加上icon.png本身一共有6張圖片.
Step 2:新建android工程,命名為GalleryDemo.
Step 3:設計UI,修改main.XML代碼如下:
<?XML version=
"1.0" encoding=
"utf-8"?>
<LinearLayout
XMLns:android=
"http://schemas.android.com/apk/res/android"
android:background="@drawable/white"
android:orIEntation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextVIEw
android:id="@+id/myTextVIEw01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:gravity="center_vertical|center_horizontal"
/>
<Gallery
android:id="@+id/myGallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
/>
</LinearLayout>
Step 4:設計主程序類GalleryDemo.Java代碼如下:
package com.android.test;
import com.android.test.R.drawable;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.VIEw;
import android.view.VIEwGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageVIEw;
public class GalleryDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentVIEw(R.layout.main);
((Gallery) findVIEwById(R.id.myGallery1)).setAdapter(new ImageAdapter(
this));
}
public class ImageAdapter extends BaseAdapter {
/* 類成員 myContext為Context父類 */
private Context myContext;
/* 使用res/drawable圖片作為圖片來源 */
private int[] myImageIds = { drawable.icon, drawable.icon2,
drawable.icon3, drawable.icon4, drawable.icon5, drawable.icon6};
/* 構造器只有一個參數,即要存儲的Context */
public ImageAdapter(Context c) {
this.myContext = c;
}
/* 返回所有已定義的圖片總數量 */
public int getCount() {
return this.myImageIds.length;
}
/* 利用getItem方法,取得目前容器中圖像的數組ID */
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* 取得目前欲顯示的圖像VIEw,傳入數組ID值使之讀取與成像 */
public View getVIEw(int position, View convertView, VIEwGroup parent) {
/* 創建一個ImageVIEw對象 */
ImageVIEw i = new ImageVIEw(this.myContext);
i.setImageResource(this.myImageIds[position]);
i.setScaleType(ImageVIEw.ScaleType.FIT_XY);
/* 設置這個ImageVIEw對象的寬高,單位為dip */
i.setLayoutParams(new Gallery.LayoutParams(120, 120));
return i;
}
/* 依據距離中央的位移量 利用getScale返回vIEws的大小(0.0f to 1.0f) */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}
}
}
Step 5:run it,效果如下圖:
注明:該代碼基本參照android SDK開發范例代碼大全.今天晚上就懶一回呵呵...