Code example for Gallery

Methods: setAdapter, setOnItemClickListener

0
 
	@Override 
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		gallery = new Gallery(this);
		Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		String[] projection = { MediaStore.Images.Media._ID };
		String selection = null;
		String[] selectionArgs = null;
		String sortOrder = null;
		Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
		gallery.setAdapter(new CursorAdapter(this, cursor, true) {
			@Override 
			public View newView(Context context, Cursor cursor, ViewGroup parent) {
				int id = cursor.getInt(0);
				ContentResolver cr = getContentResolver();
				Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
				Bitmap image = null;
 
				try { 
					image = MediaStore.Images.Media.getBitmap(cr, uri);
				} catch (Exception e) {
					Log.e("Error", "Error", e);
				} 
				ImageView imageView = new ImageView(context);
				imageView.setId(id);
				imageView.setScaleType(ScaleType.CENTER_INSIDE);
				imageView.setImageBitmap(image);
				return imageView;
			} 
 
			@Override 
			public void bindView(View view, Context context, Cursor cursor) {
				int id = cursor.getInt(0);
				ContentResolver cr = getContentResolver();
				Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
				Bitmap image = null;
				try { 
					image = MediaStore.Images.Media.getBitmap(cr, uri);
				} catch (Exception e) {
					Log.e("Error", "Error", e);
				} 
				ImageView imageView = (ImageView) view;
				imageView.setId(id);
 
				imageView.setImageBitmap(image);
			} 
		}); 
 
		gallery.setOnItemClickListener(new OnItemClickListener() {
			@Override 
			public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
				selectedImageId = v.getId();
				showDialog(DELETE_DIALOG);
			}