Android的GridView和Gallery结合Demo

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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.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列
     */
    @Override
    public 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;
        }

        @Override
        public 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;

    @Override
    public 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; 

    // 定义整型数组 即图片源

    // 声明 ImageAdapter
    public ImageAdapter(Context c) {
        mContext = c;
    }

    // 获取图片的个数
    public int getCount() {
        return ImageSource.mThumbIds.length;
    }

    // 获取图片在库中的位置
    public Object getItem(int position) {
        ownposition=position;
        return position;
    }

    // 获取图片ID
    public 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下载地址:gridGalleryDemo.zip下载

时间: 2024-07-30 15:28:16

Android的GridView和Gallery结合Demo的相关文章

Android开发学习笔记 Gallery和GridView浅析_Android

一.Gallery的简介 Gallery(画廊)是一个锁定中心条目并且拥有水平滚动列表的视图,一般用来浏览图片,并且可以响应事件显示信息.Gallery还可以和ImageSwitcher组件结合使用来实现一个通过缩略图来浏览图片的效果. Gallery常用的XML属性 属性名称 描述 android:animationDuration 设置布局变化时动画的转换所需的时间(毫秒级).仅在动画开始时计时.该值必须是整数,比如:100. android:gravity 指定在对象的X和Y轴上如何放置内

Android开发学习笔记 Gallery和GridView浅析

一.Gallery的简介 Gallery(画廊)是一个锁定中心条目并且拥有水平滚动列表的视图,一般用来浏览图片,并且可以响应事件显示信息.Gallery还可以和ImageSwitcher组件结合使用来实现一个通过缩略图来浏览图片的效果. Gallery常用的XML属性 属性名称 描述 android:animationDuration 设置布局变化时动画的转换所需的时间(毫秒级).仅在动画开始时计时.该值必须是整数,比如:100. android:gravity 指定在对象的X和Y轴上如何放置内

Android实现GridView中ImageView动态变换的方法_Android

本文实例讲述了Android实现GridView中ImageView动态变换的方法.分享给大家供大家参考.具体如下: 使用YY影音的时候,发现点击GridView的某一个Item,Item里面的图标会在按下的时候发生变换,变成另外一个图片. 自己写了一个类似的demo,具体步骤如下: 1.创建一个包含Grid的Acitity 2.创建item.xml 里面包含一个imageview和一个textview 3.自定义一个adapter,从baseadapter继承 4.在getView中为每个im

Android实现动态向Gallery中添加图片及倒影与3D效果示例_Android

本文实例讲述了Android实现动态向Gallery中添加图片及倒影与3D效果的方法.分享给大家供大家参考,具体如下: 在Android中gallery可以提供一个很好的显示图片的方式,实现上面的效果以及动态添加数据库或者网络上下载下来的图片资源.我们首先实现一个自定义的Gallery类. MyGallery.java: package nate.android.Service; import android.content.Context; import android.graphics.Ca

Android利用GridView实现单选功能

先看看GridView实现单选效果 如果是你需要的,你可以继续往下看了 实现起来比较简单,直接上代码 主Activity的布局,一个Button用来跳转到筛选Activity一个TextView用来显示筛选后的到的结果 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi

Android实现动态向Gallery中添加图片及倒影与3D效果示例

本文实例讲述了Android实现动态向Gallery中添加图片及倒影与3D效果的方法.分享给大家供大家参考,具体如下: 在Android中gallery可以提供一个很好的显示图片的方式,实现上面的效果以及动态添加数据库或者网络上下载下来的图片资源.我们首先实现一个自定义的Gallery类. MyGallery.java: package nate.android.Service; import android.content.Context; import android.graphics.Ca

Android实现GridView中ImageView动态变换的方法

本文实例讲述了Android实现GridView中ImageView动态变换的方法.分享给大家供大家参考.具体如下: 使用YY影音的时候,发现点击GridView的某一个Item,Item里面的图标会在按下的时候发生变换,变成另外一个图片. 自己写了一个类似的demo,具体步骤如下: 1.创建一个包含Grid的Acitity 2.创建item.xml 里面包含一个imageview和一个textview 3.自定义一个adapter,从baseadapter继承 4.在getView中为每个im

求android文字识别能成功的demo

问题描述 求android文字识别能成功的demo 关于android 文字识别 ,好像除了5个相关jar包以外,到现在都没找到个demo,解决这个问题 啊 解决方案 http://www.cnblogs.com/hangxin1940/archive/2012/01/13/2321507.htmlhttp://blog.csdn.net/xieyan0811/article/details/5931619http://www.pudn.com/downloads524/sourcecode/c

android,一个很简单的demo,一运行就出错,谁能帮我看看怎么回事。

问题描述 android,一个很简单的demo,一运行就出错,谁能帮我看看怎么回事. eclipse上也没有错误提示,怎么运行不了.安装好就提示停止运行. 文件 解决方案 看logcat的日志,或者进入调试模式运行,一步步调 解决方案二: 亲,绑定布局空间是要通过布局管理者来获取的,不然就是空指针错误.具体如下 解决方案三: 用调试模式调试吧,很方便的. 解决方案四: 要看log日志的啊.看日志才知道哪里出错了, 解决方案五: fragment控件初始化的问题吧 解决方案六: fragment控