Android的GridView和Gallery结合Demo
Android的GridView和Gallery结合Demo
Demo介绍:首页是一个GridView加载图片,竖屏时显示3列图片,横屏时显示4列图片;并且对图片进行大小限制和加灰色边框处理。
点击某一张图片,会链接到Gallery页面,由于Android自带的Gallery控件滑动效果很不好(滑动一次会加载好多张图片),这里对Gallery进行了扩展,滑动一次只加载一张图片。
Demo效果如下:
1、首页Activity页面,GridViewActivity.java介绍:
1 public class GridViewActivity extends Activity { 2 private DisplayMetrics dm; 3 private GridImageAdapter ia; 4 private GridView g; 5 private int imageCol = 3; 6 7 @Override 8 protected void onCreate(Bundle savedInstanceState) { 9 // TODO Auto-generated method stub 10 super.onCreate(savedInstanceState); 11 // requestWindowFeature(Window.FEATURE_NO_TITLE); 12 ia = new GridImageAdapter(this); 13 setContentView(R.layout.mygridview); 14 g = (GridView) findViewById(R.id.myGrid); 15 g.setAdapter(ia); 16 g.setOnItemClickListener(new OnItemClick(this)); 17 // 得到屏幕的大小 18 dm = new DisplayMetrics(); 19 getWindowManager().getDefaultDisplay().getMetrics(dm); 20 21 } 22 23 /** 24 * 屏幕切换时进行处理 如果屏幕是竖屏,则显示3列,如果是横屏,则显示4列 25 */ 26 @Override 27 public void onConfigurationChanged(Configuration newConfig) { 28 try { 29 30 super.onConfigurationChanged(newConfig); 31 // 如果屏幕是竖屏,则显示3列,如果是横屏,则显示4列 32 if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { 33 imageCol = 4; 34 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { 35 imageCol = 3; 36 } 37 g.setNumColumns(imageCol); 38 g.setAdapter(new ImageAdapter(this)); 39 // ia.notifyDataSetChanged(); 40 } catch (Exception ex) { 41 ex.printStackTrace(); 42 } 43 } 44 45 /** 46 * 47 * @author 空山不空 点击具体的小图片时,会链接到GridViewActivity页面,进行加载和展示 48 */ 49 public class OnItemClick implements OnItemClickListener { 50 public OnItemClick(Context c) { 51 mContext = c; 52 } 53 54 @Override 55 public void onItemClick(AdapterView aview, View view, int position, 56 long arg3) { 57 Intent intent = new Intent(); 58 intent.setClass(GridViewActivity.this, GalleryActivity.class); 59 intent.putExtra("position", position); 60 GridViewActivity.this.startActivity(intent); 61 } 62 63 private Context mContext; 64 } 65 66 /** 67 * 68 * @author 空山不空 设置GridView的图片适配器 69 */ 70 public class GridImageAdapter extends BaseAdapter { 71 72 Drawable btnDrawable; 73 74 public GridImageAdapter(Context c) { 75 mContext = c; 76 Resources resources = c.getResources(); 77 btnDrawable = resources.getDrawable(R.drawable.bg); 78 } 79 80 public int getCount() { 81 return ImageSource.mThumbIds.length; 82 } 83 84 public Object getItem(int position) { 85 return position; 86 } 87 88 public long getItemId(int position) { 89 return position; 90 } 91 92 public View getView(int position, View convertView, ViewGroup parent) { 93 ImageViewExt imageView; 94 95 if (convertView == null) { 96 imageView = new ImageViewExt(mContext); 97 // 如果是横屏,GridView会展示4列图片,需要设置图片的大小 98 if (imageCol == 4) { 99 imageView.setLayoutParams(new GridView.LayoutParams( 100 dm.heightPixels / imageCol - 6, dm.heightPixels 101 / imageCol - 6)); 102 } else {// 如果是竖屏,GridView会展示3列图片,需要设置图片的大小 103 imageView.setLayoutParams(new GridView.LayoutParams( 104 dm.widthPixels / imageCol - 6, dm.widthPixels 105 / imageCol - 6)); 106 } 107 imageView.setAdjustViewBounds(true); 108 imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 109 } else { 110 imageView = (ImageViewExt) convertView; 111 } 112 imageView.setImageResource(ImageSource.mThumbIds[position]); 113 114 return imageView; 115 } 116 117 private Context mContext; 118 } 119 }
加载GridView页面,如果屏幕是竖屏,则显示3列,如果是横屏,则显示4列;并且显示的图片加上灰色边框,这里在适配器GridImageAdapter的getView方法里引用了ImageViewExt类来对图片进行处理,这个类扩展自ImageView;点击其中的某一张图片,会跳转到GalleryActivity页面。
2、ImageViewExt.java文件
1 /** 2 * 3 * @author 空山不空 4 * 扩展ImageView类,将图片加上边框,并且设置边框为灰色 5 */ 6 public class ImageViewExt extends ImageView { 7 //将图片加灰色的边框 8 private int color; 9 10 public ImageViewExt(Context context) { 11 super(context); 12 // TODO Auto-generated constructor stub 13 color=Color.GRAY; 14 } 15 16 public ImageViewExt(Context context, AttributeSet attrs) { 17 super(context, attrs); 18 // TODO Auto-generated constructor stub 19 color=Color.GRAY; 20 } 21 22 23 @Override 24 protected void onDraw(Canvas canvas) { 25 // TODO Auto-generated method stub 26 27 super.onDraw(canvas); 28 //画边框 29 Rect rec=canvas.getClipBounds(); 30 rec.bottom--; 31 rec.right--; 32 Paint paint=new Paint(); 33 paint.setColor(color); 34 paint.setStrokeWidth(5); 35 paint.setStyle(Paint.Style.STROKE); 36 canvas.drawRect(rec, paint); 37 } 38 }
通过重载onDraw方法来画边框和设置边框颜色
3、相册GalleryActivity.java
1 /** 2 * 3 * @author 空山不空 4 * Gallery图片页面,通过Intent得到GridView传过来的图片位置,加载图片,再设置适配器 5 */ 6 public class GalleryActivity extends Activity { 7 public int i_position = 0; 8 private DisplayMetrics dm; 9 10 @Override 11 public void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 requestWindowFeature(Window.FEATURE_NO_TITLE); 14 setContentView(R.layout.mygallery); 15 dm = new DisplayMetrics(); 16 getWindowManager().getDefaultDisplay().getMetrics(dm); 17 // 获得Gallery对象 18 GalleryExt g = (GalleryExt) findViewById(R.id.ga); 19 //通过Intent得到GridView传过来的图片位置 20 Intent intent = getIntent(); 21 i_position = intent.getIntExtra("position", 0); 22 // 添加ImageAdapter给Gallery对象 23 ImageAdapter ia=new ImageAdapter(this); 24 g.setAdapter(ia); 25 g.setSelection(i_position); 26 27 //加载动画 28 Animation an= AnimationUtils.loadAnimation(this,R.anim.scale ); 29 g.setAnimation(an); 30 31 } 32 }
这里有三点:
(1)、扩展Gallery组件,即GalleryExt控件,设置滑动一次只加载一张图片,并且, 如果是第一张图片时,向左滑动会提示“已到第一页”,如果是最后一张图片时,向右滑动会提示“已到第后页”
(2)、接收GridViewActivity页面传过来的参数position,通过这个参数找到具体的图片,通过ImageAdapter适配器加载
(3)、ImageAdapter图片适配器,用来加载图片
4、GalleryExt.java文件
1 /** 2 * 3 * @author 空山不空 4 * 扩展Gallery组件,设置滑动一次只加载一张图片,并且, 5 * 如果是第一张图片时,向左滑动会提示“已到第一页” 6 * 如果是最后一张图片时,向右滑动会提示“已到第后页” 7 */ 8 public class GalleryExt extends Gallery { 9 boolean is_first=false; 10 boolean is_last=false; 11 public GalleryExt(Context context) { 12 super(context); 13 // TODO Auto-generated constructor stub 14 } 15 16 public GalleryExt(Context context,AttributeSet paramAttributeSet) 17 { 18 super(context,paramAttributeSet); 19 20 } 21 22 private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) 23 { 24 return e2.getX() > e1.getX(); 25 } 26 27 @Override 28 public boolean onFling(MotionEvent e1, MotionEvent e2, float distanceX, 29 float distanceY) { 30 //通过重构onFling方法,使Gallery控件滑动一次只加载一张图片 31 //获取适配器 32 ImageAdapter ia=(ImageAdapter)this.getAdapter(); 33 //得到当前图片在图片资源中的位置 34 int p=ia.getOwnposition(); 35 //图片的总数量 36 int count=ia.getCount(); 37 int kEvent; 38 if(isScrollingLeft(e1, e2)){ 39 //Check if scrolling left 40 if(p==0&&is_first){ 41 //在第一页并且再往左移动的时候,提示 42 Toast.makeText(this.getContext(), "已到第一页", Toast.LENGTH_SHORT).show(); 43 }else if(p==0){ 44 //到达第一页时,把is_first设置为true 45 is_first=true; 46 }else{ 47 is_last=false; 48 } 49 50 kEvent = KeyEvent.KEYCODE_DPAD_LEFT; 51 } else{ 52 //Otherwise scrolling right 53 if(p==count-1&&is_last){ 54 Toast.makeText(this.getContext(), "已到最后一页", Toast.LENGTH_SHORT).show(); 55 }else if( p==count-1){ 56 is_last=true; 57 }else{ 58 is_first=false; 59 } 60 61 kEvent = KeyEvent.KEYCODE_DPAD_RIGHT; 62 } 63 onKeyDown(kEvent, null); 64 return true; 65 }
5、ImageAdapter.java文件
1 /** 2 * 3 * @author 空山不空 4 * 图片适配器,用来加载图片 5 */ 6 public class ImageAdapter extends BaseAdapter { 7 //图片适配器 8 // 定义Context 9 private int ownposition; 10 11 12 public int getOwnposition() { 13 return ownposition; 14 } 15 16 public void setOwnposition(int ownposition) { 17 this.ownposition = ownposition; 18 } 19 20 private Context mContext; 21 22 // 定义整型数组 即图片源 23 24 // 声明 ImageAdapter 25 public ImageAdapter(Context c) { 26 mContext = c; 27 } 28 29 // 获取图片的个数 30 public int getCount() { 31 return ImageSource.mThumbIds.length; 32 } 33 34 // 获取图片在库中的位置 35 public Object getItem(int position) { 36 ownposition=position; 37 return position; 38 } 39 40 // 获取图片ID 41 public long getItemId(int position) { 42 ownposition=position; 43 return position; 44 } 45 46 public View getView(int position, View convertView, ViewGroup parent) { 47 48 49 ownposition=position; 50 ImageView imageview = new ImageView(mContext); 51 imageview.setBackgroundColor(0xFF000000); 52 imageview.setScaleType(ImageView.ScaleType.FIT_CENTER); 53 imageview.setLayoutParams(new GalleryExt.LayoutParams( 54 LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 55 56 imageview.setImageResource(ImageSource.mThumbIds[position]); 57 // imageview.setAdjustViewBounds(true); 58 // imageview.setLayoutParams(new GridView.LayoutParams(320, 480)); 59 // imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 60 return imageview; 61 } 62 }
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页面
1 <?xml version="1.0" encoding="utf-8"?> 2 3 4 <GridView xmlns:android="http://schemas.android.com/apk/res/android" 5 android:id="@+id/myGrid" 6 android:layout_width="fill_parent" 7 android:layout_height="fill_parent" 8 android:verticalSpacing="6dp" 9 android:numColumns="3" 10 android:paddingTop="5dp" 11 android:stretchMode="columnWidth" 12 android:gravity="fill_vertical|fill_horizontal" 13 />
(3)mygallery.xml,加载图片页面
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="horizontal" android:layout_width="match_parent" 4 android:layout_height="match_parent" android:gravity="center" 5 android:padding="10dip"> 6 <RelativeLayout android:layout_width="wrap_content" 7 android:layout_height="wrap_content" android:padding="2dip" 8 android:background="#000000"> 9 10 <com.ajie.GalleryExt android:id="@+id/ga" 11 android:layout_width="fill_parent" android:layout_height="fill_parent" 12 android:spacing="16dp" /> 13 </RelativeLayout> 14 </LinearLayout>
Demo下载地址:<a href="https://files.cnblogs.com/fbsk/gridGalleryDemo.zip"> gridGalleryDemo.zip下载</a>
转自:http://www.cnblogs.com/fbsk/archive/2011/10/10/2205776.html