【问题标题】:How to Populate a GridView with Drawables One Cell at a time如何使用 Drawables 一次填充一个单元格的 GridView
【发布时间】:2015-07-04 21:57:11
【问题描述】:

我想知道是否有人知道如何设置适配器以一次填充 GridView 一个单元格。我设法创建了一个自定义适配器,它将填充每个单元格,但我想根据点击一次一个单元格来完成它。换句话说,您单击一个按钮,一个图像会填充网格视图中的第一个单元格。您再次按下按钮,图像会填充网格视图中的第二个单元格,依此类推。我的适配器代码如下所示。

public class ImageAdapter extends BaseAdapter {

    private Context myContext;


    public ImageAdapter(Context c) {
        myContext = c;
    }

    public int getCount() {
        return imageId;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    //Create a new ImageView for each Item referenced by the adapter

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView image;
        if (convertView == null) {
            //If Image is not Recycled, set these attributes
            image = new ImageView(myContext);
            image.setLayoutParams(new GridView.LayoutParams(85,85));
            image.setScaleType(ImageView.ScaleType.CENTER_CROP);
            image.setPadding(4,4,4,4);
        } else {
            image = (ImageView) convertView;
        }
        image.setImageResource(imageId);
        return image;
    }


    //Reference to The Images
    private Integer imageId =
            R.drawable.red_ball;

}

【问题讨论】:

    标签: android image gridview adapter baseadapter


    【解决方案1】:

    保留一个计数器并将其初始化为零。

    在您的适配器中,如果位置小于计数器,则调用 image.setImageResource(imageId) 否则调用 image.setImageDrawable(null)。

    当您按下按钮时,递增计数器并调用 adapter.notifyDatasetChanged()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2012-03-30
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      相关资源
      最近更新 更多