在 Android 裡使用 Gallery
在看過 AdapterView 裡的 ListView, GridView 和 Spinner 後,只剩下 Gallery 最後一位成員。
Gallery 的特色就是水平方向 scroll 清單,選定的子元件置中對齊,目前看來 Gallery 都是用 ImageView 作為子元件。
XML layout 設定如下:
還有一個位於 res/values/attrs.xml 的 XML 設定檔:
Gallery 的特色就是水平方向 scroll 清單,選定的子元件置中對齊,目前看來 Gallery 都是用 ImageView 作為子元件。
XML layout 設定如下:
另外使用一個 ImageView 用來顯示被選取的 Gallery 照片。
還有一個位於 res/values/attrs.xml 的 XML 設定檔:
Activity 程式如下:
public class A_Gallery extends Activity {
private Integer[] icons = new Integer[] {
R.drawable.wanwan_01, R.drawable.wanwan_02, R.drawable.wanwan_03,
R.drawable.wanwan_04, R.drawable.wanwan_05, R.drawable.wanwan_06,
R.drawable.wanwan_07, R.drawable.wanwan_08, R.drawable.wanwan_09,
R.drawable.wanwan_10, R.drawable.wanwan_11, R.drawable.wanwan_12,
R.drawable.wanwan_13, R.drawable.wanwan_14, R.drawable.wanwan_15,
R.drawable.wanwan_16, R.drawable.wanwan_17, R.drawable.wanwan_18
};
private int galleryItemBackground;
private A_Gallery() {
super();
// Gallery 預設使用 Theme_galleryItemBackground 作為
// 每個 View 子元件(也就是每個 ImageView)的背景 // 如果不要用 Theme_galleryItemBackgroun,得一併修改 Gallery 的一些屬性 // TODO 奇怪的使用方法,留著以後再研究 TypedArray a = obtainStyledAttributes(R.styleable.A_Gallery); this.galleryItemBackground = a.getResourceId( R.styleable.A_Gallery_android_galleryItemBackground, 0); // 一定要 recycle! a.recycle(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery gallery = (Gallery) this.findViewById(R.id.gallery); // 當點擊 Gallery 裡的每張照片時,將該照片顯示到 Gallery 下方的 ImageView 裡 final ImageView iv = (ImageView) this.findViewById(R.id.img); gallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { iv.setImageResource(icons[position]); // 一樣使用 Gallery 子元件的背景 iv.setBackgroundResource(galleryItemBackground); } }); // 自訂 ImageAdapter gallery.setAdapter(new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView iv = new ImageView(A_Gallery.this); iv.setImageResource(icons[position]); // 用於 Gallery 的 View 子元件需透過 LayoutParams 設定配置 iv.setLayoutParams(new Gallery.LayoutParams(100, 100)); // 維持比例 iv.setScaleType(ImageView.ScaleType.FIT_XY); // Gallery 專用的背景 iv.setBackgroundResource(galleryItemBackground); return iv; } @Override public int getCount() { return icons.length; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } }); } }
No comments:
Post a Comment