GridView不显示图像

时间:2017-08-21 05:56:09

标签: android

我想在我的应用程序中创建产品库,所以我创建了Gallery

活动并在图库布局中插入网格视图

并使用Base适配器显示数据,但是当我运行应用程序空白活动时显示

自定义适配器代码:

public class GalleryManager extends BaseAdapter {
    Context context;
    List<Drawable> list;
    int[] id;

    public GalleryManager(Context context , int[] id ) {
        this.context = context;
        //this.list = list;
        this.id = id;
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(context);
        imageView.setImageResource(id[position]);
        return imageView;
    }
}

在图库活动中使用:

gridView = (GridView) findViewById(R.id.galleryGridView);
        int id[] = {
                R.drawable.gallery1,
                R.drawable.gallery2,
                R.drawable.gallery3
        };
        gridView.setAdapter(new GalleryManager(this,id));

在布局中查看:

<GridView
        android:id="@+id/galleryGridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp" />

3 个答案:

答案 0 :(得分:2)

对您的getCount()方法使用数组长度,更改您的getCount方法

@Override
    public int getCount() {
        return id.length;
    }

我希望这对你有所帮助。

答案 1 :(得分:0)

发生这种情况是因为您没有在自定义适配器中正确返回数组大小和数组项。

更新你的getCount方法以返回drawable的数量:

@Override
public int getCount() {
    return list.getSize();
}

更新你的getItem方法以返回你的DrawableItem:

@Override
public Object getItem(int position) {
    return list.get(position);
}

答案 2 :(得分:0)

 public GalleryManager(Context context , int[] id ,List<Drawable> list) {
        this.context = context;
        this.list = list;
        this.id = id;
    }

更新您的getCount方法,如下所示:

@Override
public int getCount() {
    return list.size();
}

更新你的getItem方法:

 @Override
    public Object getItem(int position) {
        return list.get(position);
    }