我是Android新手,想要通过意图从手机图库加载图片,并希望在gridView
上显示列表项。
但是当我在选择后加载图库时,图像未显示。
活动
private static final int CODE = 0;
public GridView gridView;
public Uri selectedImageUri;
ImageAdapter imageAdapter;
...
gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
imageAdapter = new ImageAdapter(this);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Toast.makeText(MainActivity.this, "" + position + "",
Toast.LENGTH_LONG).show();
}
});
Button loadImageButton = (Button) findViewById(R.id.load_image_button);
loadImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
Picture"), CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == CODE && resultCode == RESULT_OK && intent != null) {
selectedImageUri = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
objImageAdapter.addToList(picturePath);
cursor.close();
imageView = (ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
适配器类
public class ImageAdapter extends BaseAdapter {
public ImageView imageView;
private Context vContext;
ArrayList<String> arrayList = new ArrayList<String>();
public ImageAdapter(Context context) {
this.vContext = context;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return position;
}
public void addToList(String stringPath) {
this.arrayList.add(stringPath);
this.notifyDataSetChanged();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(vContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(2, 2, 2, 2);
} else {
imageView = (ImageView) convertView;
}
String path = arrayList.get(position);
Bitmap bitmap = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(bitmap);
return imageView;