2011年5月23日 星期一

Gallery物件

Gallery物件畫廊,大部分用於顯示圖片
Gallery.java
    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));
    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) {
            // function
        }
    }

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;
        private Integer[] mImageIds = {
            R.drawable.sample01,        R.drawable.sample02,        R.drawable.sample03,
            R.drawable.sample04,        R.drawable.sample05,        R.drawable.sample06,
            R.drawable.sample07,        R.drawable.sample08,        R.drawable.sample09     };
   
        // 建構子,當new新物件時會進到這裡做初始化的動作
        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
            mGalleryItemBackground = a.getResourceId(
                R.styleable.HelloGallery_android_galleryItemBackground, 0);
            a.recycle();
        }
   
        public int getCount() {    return mImageIds.length;    }
        public Object getItem(int position) {    return position;    }
        public long getItemId(int position) {    return position;    }
   
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);
            i.setImageResource(mImageIds[position]);
            i.setLayoutParams(new Gallery.LayoutParams(320, 480));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setBackgroundResource(mGalleryItemBackground);
            return i;
        }
    }

main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <Gallery xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
values的資料夾下新增HelloGallery的style
attrs.xml
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="HelloGallery">
            <attr name="android:galleryItemBackground" />
        </declare-styleable>
    </resources>

沒有留言:

張貼留言