Android--图片集

一. 实现效果

  安卓系统中的相册集效果图,左右滑动可以查看上一张或者下一张图片

   

二. 布局代码

<?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张图片

其中最重要的方法就是,用于返回图片视图

@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;
}

  

四. 设置数据绑定

Gallery gePics=(Gallery)findViewById(R.id.gePics);
gePics.setAdapter(new ImageAdapter(this));

  使用setAdapter()方法用于来设定数据源

原文地址:https://www.cnblogs.com/qingyuan/p/4246645.html