標籤:
一. 實現效果
安卓系統中的相簿集,左右滑動可以查看上一張或者下一張圖片
二. 布局代碼
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Gallery android:id="@+id/gePics" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
三. 自訂Adapter
package com.git.ch3;import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.Gallery;import android.widget.ImageView;public class ImageAdapter extends BaseAdapter { private Context myContext; private Integer[] myImages={ R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4, R.drawable.pic5, R.drawable.pic6, R.drawable.pic7, R.drawable.pic8 }; public ImageAdapter(Context context) { this.myContext=context; } @Override public int getCount() { return myImages.length; } @Override public Object getItem(int arg0) { return myImages[arg0]; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { ImageView view=new ImageView(this.myContext); view.setImageResource(this.myImages[arg0]); view.setScaleType(ImageView.ScaleType.FIT_XY); view.setLayoutParams(new Gallery.LayoutParams(300, 200)); return view; }}自訂Adapter
自訂Adapter主要適用於指定了圖片返回的大小,以及指定相簿集中顯示哪些圖片,這裡在系統工程目錄(drawable-mdpi)中添加了8張圖片
其中最重要的方法就是,用於返回圖片視圖
@Overridepublic View getView(int arg0, View arg1, ViewGroup arg2) { ImageView view=new ImageView(this.myContext); view.setImageResource(this.myImages[arg0]); view.setScaleType(ImageView.ScaleType.FIT_XY); view.setLayoutParams(new Gallery.LayoutParams(300, 200)); return view;}
四. 設定資料繫結
Gallery gePics=(Gallery)findViewById(R.id.gePics);gePics.setAdapter(new ImageAdapter(this));
使用setAdapter()方法用於來設定資料來源
Android--圖片集