Android的GridView和Gallery結合Demo

來源:互聯網
上載者:User

Demo介紹:首頁是一個GridView載入圖片,豎屏時顯示3列圖片,橫屏時顯示4列圖片;並且對圖片進行大小限制和加灰色邊框處理。

點擊某一張圖片,會連結到Gallery頁面,由於Android內建的Gallery控制項滑動效果很不好(滑動一次會載入好多張圖片),這裡對Gallery進行了擴充,滑動一次只載入一張圖片。

Demo效果如下:

 

1、首頁Activity頁面,GridViewActivity.java介紹:

public class GridViewActivity extends Activity {private DisplayMetrics dm;private GridImageAdapter ia;private GridView g;private int imageCol = 3;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);// requestWindowFeature(Window.FEATURE_NO_TITLE);ia = new GridImageAdapter(this);setContentView(R.layout.mygridview);g = (GridView) findViewById(R.id.myGrid);g.setAdapter(ia);g.setOnItemClickListener(new OnItemClick(this));// 得到螢幕的大小dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);}/** * 螢幕切換時進行處理 如果螢幕是豎屏,則顯示3列,如果是橫屏,則顯示4列 */@Overridepublic void onConfigurationChanged(Configuration newConfig) {try {super.onConfigurationChanged(newConfig);// 如果螢幕是豎屏,則顯示3列,如果是橫屏,則顯示4列if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {imageCol = 4;} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {imageCol = 3;}g.setNumColumns(imageCol);g.setAdapter(new ImageAdapter(this));// ia.notifyDataSetChanged();} catch (Exception ex) {ex.printStackTrace();}}/** *  * @author 空山不空 點擊具體的小圖片時,會連結到GridViewActivity頁面,進行載入和展示 */public class OnItemClick implements OnItemClickListener {public OnItemClick(Context c) {mContext = c;}@Overridepublic void onItemClick(AdapterView aview, View view, int position,long arg3) {Intent intent = new Intent();intent.setClass(GridViewActivity.this, GalleryActivity.class);intent.putExtra("position", position);GridViewActivity.this.startActivity(intent);}private Context mContext;}/** *  * @author 空山不空 設定GridView的圖片適配器 */public class GridImageAdapter extends BaseAdapter {Drawable btnDrawable;public GridImageAdapter(Context c) {mContext = c;Resources resources = c.getResources();btnDrawable = resources.getDrawable(R.drawable.bg);}public int getCount() {return ImageSource.mThumbIds.length;}public Object getItem(int position) {return position;}public long getItemId(int position) {return position;}public View getView(int position, View convertView, ViewGroup parent) {ImageViewExt imageView;if (convertView == null) {imageView = new ImageViewExt(mContext);// 如果是橫屏,GridView會展示4列圖片,需要設定圖片的大小if (imageCol == 4) {imageView.setLayoutParams(new GridView.LayoutParams(dm.heightPixels / imageCol - 6, dm.heightPixels/ imageCol - 6));} else {// 如果是豎屏,GridView會展示3列圖片,需要設定圖片的大小imageView.setLayoutParams(new GridView.LayoutParams(dm.widthPixels / imageCol - 6, dm.widthPixels/ imageCol - 6));}imageView.setAdjustViewBounds(true);imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); } else {imageView = (ImageViewExt) convertView;}imageView.setImageResource(ImageSource.mThumbIds[position]);return imageView;}private Context mContext;}}

載入GridView頁面,如果螢幕是豎屏,則顯示3列,如果是橫屏,則顯示4列;並且顯示的圖片加上灰色邊框,這裡在適配器GridImageAdapter的getView方法裡引用了ImageViewExt類來對圖片進行處理,這個類擴充自ImageView;點擊其中的某一張圖片,會跳轉到GalleryActivity頁面。

2、ImageViewExt.java檔案

/** *  * @author 空山不空 * 擴充ImageView類,將圖片加上邊框,並且設定邊框為灰色 */public class ImageViewExt extends ImageView { //將圖片加灰色的邊框    private int color;    public ImageViewExt(Context context) {        super(context);       // TODO Auto-generated constructor stub        color=Color.GRAY;  }       public ImageViewExt(Context context, AttributeSet attrs) {         super(context, attrs);        // TODO Auto-generated constructor stub         color=Color.GRAY;   }        @Override     protected void onDraw(Canvas canvas) {         // TODO Auto-generated method stub                   super.onDraw(canvas);            //畫邊框         Rect rec=canvas.getClipBounds();        rec.bottom--;        rec.right--;        Paint paint=new Paint();        paint.setColor(color);         paint.setStrokeWidth(5);        paint.setStyle(Paint.Style.STROKE);        canvas.drawRect(rec, paint);    }}

通過重載onDraw方法來畫邊框和設定邊框顏色

3、相簿GalleryActivity.java

/** *  * @author 空山不空 * Gallery圖片頁面,通過Intent得到GridView傳過來的圖片位置,載入圖片,再設定適配器 */public class GalleryActivity extends Activity {public int i_position = 0;private DisplayMetrics dm;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mygallery); dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);// 獲得Gallery對象GalleryExt  g = (GalleryExt) findViewById(R.id.ga);//通過Intent得到GridView傳過來的圖片位置Intent intent = getIntent();i_position = intent.getIntExtra("position", 0); // 添加ImageAdapter給Gallery對象ImageAdapter ia=new ImageAdapter(this);g.setAdapter(ia); g.setSelection(i_position);   //載入動畫 Animation an= AnimationUtils.loadAnimation(this,R.anim.scale );        g.setAnimation(an); } }

 這裡有三點:

(1)、擴充Gallery組件,即GalleryExt控制項,設定滑動一次只載入一張圖片,並且, 如果是第一張圖片時,向左滑動會提示“已到第一頁”,如果是最後一張圖片時,向右滑動會提示“已到第後頁”

(2)、接收GridViewActivity頁面傳過來的參數position,通過這個參數找到具體的圖片,通過ImageAdapter適配器載入

(3)、ImageAdapter圖片適配器,用來載入圖片

4、GalleryExt.java檔案

/** *  * @author 空山不空 * 擴充Gallery組件,設定滑動一次只載入一張圖片,並且, * 如果是第一張圖片時,向左滑動會提示“已到第一頁” * 如果是最後一張圖片時,向右滑動會提示“已到第後頁” */public class GalleryExt extends Gallery {    boolean is_first=false;    boolean is_last=false;public GalleryExt(Context context) {super(context);// TODO Auto-generated constructor stub}public GalleryExt(Context context,AttributeSet paramAttributeSet) {       super(context,paramAttributeSet); }private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2)   {       return e2.getX() > e1.getX();    } @Override    public boolean onFling(MotionEvent e1, MotionEvent e2, float distanceX,                    float distanceY) {  //通過重構onFling方法,使Gallery控制項滑動一次只載入一張圖片 //擷取適配器 ImageAdapter ia=(ImageAdapter)this.getAdapter();//得到當前圖片在圖片資源中的位置 int p=ia.getOwnposition(); //圖片的總數量 int count=ia.getCount();  int kEvent;    if(isScrollingLeft(e1, e2)){    //Check if scrolling left    if(p==0&&is_first){  //在第一頁並且再往左移動的時候,提示  Toast.makeText(this.getContext(), "已到第一頁", Toast.LENGTH_SHORT).show();  }else if(p==0){  //到達第一頁時,把is_first設定為true  is_first=true;  }else{  is_last=false;  }     kEvent = KeyEvent.KEYCODE_DPAD_LEFT;     }  else{     //Otherwise scrolling right       if(p==count-1&&is_last){  Toast.makeText(this.getContext(), "已到最後一頁", Toast.LENGTH_SHORT).show();  }else if( p==count-1){  is_last=true;  }else{  is_first=false;  }      kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;       }    onKeyDown(kEvent, null);    return true;      }

5、ImageAdapter.java檔案

/** *  * @author 空山不空 *  圖片適配器,用來載入圖片 */public class ImageAdapter extends BaseAdapter {//圖片適配器// 定義Context private int ownposition; public int getOwnposition() {return ownposition;}public void setOwnposition(int ownposition) {this.ownposition = ownposition;}private Context mContext; // 定義整型數組 即圖片源// 聲明 ImageAdapterpublic ImageAdapter(Context c) {mContext = c;}// 擷取圖片的個數public int getCount() {return ImageSource.mThumbIds.length;}// 擷取圖片在庫中的位置public Object getItem(int position) { ownposition=position;return position;}// 擷取圖片IDpublic long getItemId(int position) {ownposition=position; return position;}public View getView(int position, View convertView, ViewGroup parent) { ownposition=position;ImageView imageview = new ImageView(mContext);imageview.setBackgroundColor(0xFF000000);imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);imageview.setLayoutParams(new GalleryExt.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));imageview.setImageResource(ImageSource.mThumbIds[position]);// imageview.setAdjustViewBounds(true);// imageview.setLayoutParams(new GridView.LayoutParams(320, 480));// imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);return imageview;}}

6、設定檔

(1)AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.ajie"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon"  android:label="@string/app_name"> <activity android:name=".GalleryActivity"  android:label="@string/title"  />  <activity android:name=".GridViewActivity"  android:label="@string/app_name"   android:configChanges="orientation|keyboardHidden" >                 <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>      </activity>      </application></manifest> 

(2)mygridview.xml,即GridView頁面

<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/myGrid"android:layout_width="fill_parent" android:layout_height="fill_parent"    android:verticalSpacing="6dp"      android:numColumns="3"        android:paddingTop="5dp"    android:stretchMode="columnWidth"      android:gravity="fill_vertical|fill_horizontal"     />

(3)mygallery.xml,載入圖片頁面

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal" android:layout_width="match_parent"android:layout_height="match_parent" android:gravity="center"android:padding="10dip"><RelativeLayout android:layout_width="wrap_content"android:layout_height="wrap_content" android:padding="2dip"android:background="#000000"><com.ajie.GalleryExt android:id="@+id/ga"android:layout_width="fill_parent" android:layout_height="fill_parent"android:spacing="16dp" /></RelativeLayout></LinearLayout>

Demo:<a href="http://files.cnblogs.com/fbsk/gridGalleryDemo.zip"> gridGalleryDemo.zip下載</a>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.