在GridView中设置图像Uri

时间:2015-11-16 14:45:25

标签: android gridview uri gallery adapter

我尝试使用其uri将手机图库中的图像添加到gridView中。 不幸的是,它没有做任何事情,我似乎无法找到一种方法让它发挥作用。

我的适配器:

public class ImageGridAdapter extends BaseAdapter {


public Uri imageUri;


private Context mContext;

public ImageGridAdapter(Context c) {
    this.mContext = c;
}

@Override
public int getCount() {

    return 0;
}

@Override
public Object getItem(int position) {

    return null;
}

@Override
public long getItemId(int position) {

    return 0;
}


public View getView(int position, View convertView, ViewGroup parent) {

    imageUri = PictureGroupActivity.selectedImage;


    ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageURI(null);
    imageView.setImageURI(imageUri);

    return imageView;
   }
}

adpater应该从onActivtyResult获取imageUri:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    gridView = (GridView)findViewById(R.id.picture_group_gridView);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Toast.makeText(PictureGroupActivity.this, "selectedImage ma hodnotu: " + selectedImage, Toast.LENGTH_SHORT).show();


    }
}

我已将myCreate中的gridView设置为我的活动内容:

GridView gridView = (GridView)findViewById(R.id.picture_group_gridView);
    gridView.setAdapter(new ImageGridAdapter(this));

    gridView.invalidateViews();

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(PictureGroupActivity.this, "You clicked " + position, Toast.LENGTH_SHORT).show();
        }
    });

从图库中选择照片时,gridView仍为空。你如何让它发挥作用?我究竟做错了什么 ?提前谢谢。

2 个答案:

答案 0 :(得分:0)

如果您始终从getCount()返回0,那么您的列表将始终为空。同样,您需要从getItem()返回一些内容,以便您的View知道哪些数据与哪个列表项相关联。您可能希望使用更具体的Adapter实现,例如ArrayAdapter,可以为您处理其中一些。

答案 1 :(得分:0)

dict