GridView与ListView基本相似。
第一步就是创建适配器,实现四个方法。
package com.example.myapplication.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import com.example.myapplication.utils.pexel.ScreenUtils;
import java.util.List;
public class GirdViewAdapter extends BaseAdapter {
private List<Bitmap> bitmapList;
private Context context;
public GirdViewAdapter(Context context, List<Bitmap> list){
bitmapList = list;
this.context = context;
}
@Override
public int getCount() {
return bitmapList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int position, View contentView, ViewGroup viewGroup) {
ImageView showImageView = null;
int density = (int) ScreenUtils.getDeviceDensity(context);
if(contentView == null){
showImageView = new ImageView(context);
showImageView.setLayoutParams(new GridView.LayoutParams(120*density,140*density)); //设置布局图片
showImageView.setScaleType(ImageView.ScaleType.FIT_XY); //设置图片显示比例
}else {
showImageView = (ImageView) contentView;
}
showImageView.setBackgroundColor(Color.BLACK);
showImageView.setImageBitmap(bitmapList.get(position));
return showImageView;
}
}
第二步在getView()方法中动态产生一些用于展示要选择的图片。
@Override
public View getView(int position, View contentView, ViewGroup viewGroup) {
ImageView showImageView = null;
int density = (int) ScreenUtils.getDeviceDensity(context);
if(contentView == null){
showImageView = new ImageView(context);
showImageView.setLayoutParams(new GridView.LayoutParams(120*density,140*density)); //设置布局图片
showIma