Can't resize image in android without loosing content - android

I have some images of 400x550 (wxh) size. I want to resize them to 200 x 300 to display them in grid view of two columns. But images are not fitting into ImageView of grid completely.
for example I have this image
After resizing it to 200 x 300 it looks like this in grid
As you can see content is not fitting in image completely.
Here are my code fragments.
frame_layout_gallery.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="#+id/imageViewGallery"
android:layout_width="300dp"
android:layout_height="200dp"
android:scaleType="centerCrop"/>
</FrameLayout>
ImageAdapter:
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = inflater.inflate(R.layout.frame_layout_gallery, null);
} else {
grid = (View) convertView;
}
ImageView imageView = (ImageView) grid.findViewById(R.id.imageViewGallery);
Bitmap mBitmap = BitmapFactory.decodeResource(mContext.getResources(), imageSource[position]);
Bitmap imageBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 300, false);
imageView.setImageBitmap(imageBitmap);
return grid;
}
I have tried other options of scaling image as well but none of them seems to be working.
like
public static Bitmap scaleDown(Bitmap realImage, float maxWidth, float maxHeight,
boolean filter) {
float wRatio = (float) maxWidth / realImage.getWidth();
float hRatio = (float) maxHeight / realImage.getHeight();
int width = Math.round((float) wRatio * realImage.getWidth());
int height = Math.round((float) hRatio * realImage.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
height, filter);
return newBitmap;
}

Ok I'll post what I did, it's in gridView and made for list of images but you can easily adapt it.
PhotoScaleAdapter:
public class PhotoScaleAdapter extends BaseAdapter {
static class ViewHolder {
ImageView image;
}
List<MediaFile> mListMedia;
Context mContext;
LayoutInflater mInflater;
public PhotoScaleAdapter(Context context, List<MediaFile> mediaFiles){
mContext = context;
mListMedia = mediaFiles;
mInflater = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
return mListMedia.size();
}
#Override
public Object getItem(int position) {
return mListMedia.get(position);
}
#Override
public long getItemId(int position) {
return mListMedia.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder = null;
if (view == null) {
view = mInflater.inflate(R.layout.scale_image, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
String path = mListMedia.get(position).getPath();
Bitmap bitmap;
bitmap = BitmapHelper.resizeBitmap(path, 400, 1);
holder.image.setImageBitmap(bitmap);
holder.image.setScaleType(ImageView.ScaleType.FIT_XY);
holder.image.setAdjustViewBounds(true);
if(mListMedia.get(position).isSelected()){
LinearLayout linearLayout = (LinearLayout) holder.image.getParent();
linearLayout.setBackgroundColor(mContext.getResources().getColor(R.color.colorAccent));
}
else{
LinearLayout linearLayout = (LinearLayout) holder.image.getParent();
linearLayout.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
}
return view;
}
}
scale_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
>
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
and in final activity/fragment… images are in gridView:
<GridView
android:id="#+id/grid_saisie_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="true"
android:clickable="true"
/>

Related

How to set width and height of cell item in GridView programmatically in Android

I am trying to set a dynamic width and height of my GridView's items, this is my code:
class GridAdapter extends BaseAdapter {
private Context context;
private GridAdapter(Context context, List<ParseObject> objects) {
super();
this.context = context;
}
// CONFIGURE CELL
#Override
public View getView(int position, View cell, ViewGroup parent) {
if (cell == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cell = inflater.inflate(R.layout.cell_post_search, null);
}
//-----------------------------------------------
// MARK - INITIALIZE VIEWS
//-----------------------------------------------
ImageView postImg = cell.findViewById(R.id.cpsPostImg);
ImageView videoicon = cell.findViewById(R.id.cpsVideoIcon);
...
return cell;
}
#Override public int getCount() { return postsArray.size(); }
#Override public Object getItem(int position) { return postsArray.get(position); }
#Override public long getItemId(int position) { return position; }
}
// Set Adapter
postsGridView.setAdapter(new GridAdapter(ctx, postsArray));
// Set number of Columns accordingly to the device used
float scalefactor = getResources().getDisplayMetrics().density * screenW/3; // LET'S PRETEND MY screenW = 720, this value whoudl, be 240, which is the width i need for my cell
int number = getWindowManager().getDefaultDisplay().getWidth();
int columns = (int) ((float) number / scalefactor);
postsGridView.setNumColumns(columns);
Log.i(Configurations.TAG, "SCALE FACTOR: " + scalefactor);
And here's my custom cell_post_search.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/cpsCellLayout"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<ImageView
android:id="#+id/cpsPostImg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#c1c1c1"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/cpsVideoIcon"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_alignEnd="#+id/cpsPostImg"
android:layout_alignParentTop="true"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:visibility="invisible"
app:srcCompat="#drawable/play_butt"/>
<ImageView
android:id="#+id/cpsWhiteFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="#drawable/white_frame"/>
</RelativeLayout>
</RelativeLayout>
I get 480.0 as scale factor in my Logcat, which is not the right size I need (in my case it should be 240). Anyway, I've also tried to do this:
int columns = (int) ((float) number / (scalefactor/2));
So the scalefactor = 240, but it doesn't matter, because I need my cell's item to be square size, so basically: WIDTH = screenWidth/3, HEIGHT = screenWidth/3.
It doesn't work properly, my GridView shows 3 columns but cells get stretched in width - height looks fine - as shown here:
Is there a way to edit my code and make cells size correctly, as square images, 3 columns, based on the device size?
Try This
class GridAdapter extends BaseAdapter {
private Context context;
private GridAdapter(Context context, List<ParseObject> objects) {
super();
this.context = context;
}
// CONFIGURE CELL
#Override
public View getView(int position, View cell, ViewGroup parent) {
if (cell == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cell = inflater.inflate(R.layout.cell_post_search, null);
}
//-----------------------------------------------
// MARK - INITIALIZE VIEWS
//-----------------------------------------------
ImageView postImg = cell.findViewById(R.id.cpsPostImg);
ImageView videoicon = cell.findViewById(R.id.cpsVideoIcon);
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
postImg.getLayoutParams().height = width / 3;
...
return cell;
}
#Override public int getCount() { return postsArray.size(); }
#Override public Object getItem(int position) { return postsArray.get(position); }
#Override public long getItemId(int position) { return position; }
}
Also, in your XML layout, add android:numColumns="3":
<GridView
android:id="#+id/upPostsGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"/>

Adapter is returning the same item

I am using a ListView to display items in it, this is the layout of the cells:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lon"
android:id="#+id/textView5"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/foto"
android:layout_alignParentTop="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lat"
android:id="#+id/textView6"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textlon"
android:layout_alignBottom="#+id/foto"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textlat"
android:layout_alignTop="#+id/textlon"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Like every ListView, it needs an adapter:
public class FotoAdapter extends BaseAdapter {
private ArrayList<BeanFotos> fotos;
private LayoutInflater inflater=null;
Context c;
public FotoAdapter(Context c, ArrayList<BeanFotos> fotos){
this.fotos=fotos;
inflater=LayoutInflater.from(c);
this.c=c;
}
#Override
public int getCount() {
//this returns the proper size of the array, if I have 3 photos it returns 3
Log.i("David", "In adapter, the size of the array is: "+fotos.size());
return fotos.size();
}
#Override
public Object getItem(int position) {
//this is never called
Log.i("David", "returning item "+position);
return fotos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
//This returns 0 always
Log.i("David", "returning position "+position);
int bmWidth=fotos.get(position).getFoto().getWidth();
int bmHeight=fotos.get(position).getFoto().getHeight();
int ivWidth;
int ivHeigth;
int new_width;
int new_height;
convertView=inflater.inflate(R.layout.foto_layout, null);
holder=new ViewHolder();
holder.lat=(TextView)convertView.findViewById(R.id.textlat);
holder.lon=(TextView)convertView.findViewById(R.id.textlon);
holder.foto=(ImageView)convertView.findViewById(R.id.foto);
ivWidth=dpToPx(80);
ivHeigth=dpToPx(80);
new_width=ivWidth;
new_height = (int) Math.floor((double) bmHeight *( (double) new_width / (double) bmWidth));
Bitmap newbitMap = Bitmap.createScaledBitmap(fotos.get(position).getFoto(), new_width, new_height, true);
holder.lat.setText(fotos.get(position).getLatitud().toString());
holder.lon.setText(fotos.get(position).getLongitud().toString());
holder.foto.setImageBitmap(newbitMap);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private int dpToPx(int dp)
{
float density = c.getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
static class ViewHolder {
public TextView lat;
public TextView lon;
public ImageView foto;
}
}
If i set a debug point where the photos are taken, I can see the different photographs I have taken, but in the ListView it displays the same photo (the first one). If I set a debug point in the adapter, the array that stores the object containing the photographs has the proper size, and the photographs stored are different...but the list view shows the same photograph always, despite it shows the proper number of rows.
Why is this happening? how can I fix it? Any help?
Thank you.
try to put list of below code outside the if else condition from if block,
int bmWidth=fotos.get(position).getFoto().getWidth();
int bmHeight=fotos.get(position).getFoto().getHeight();
ivWidth=dpToPx(80);
ivHeigth=dpToPx(80);
new_width=ivWidth;
new_height = (int) Math.floor((double) bmHeight *( (double) new_width / (double) bmWidth));
Bitmap newbitMap =Bitmap.createScaledBitmap(fotos.get(position).getFoto(), new_width, new_height, true);
holder.lat.setText(fotos.get(position).getLatitud().toString());
holder.lon.setText(fotos.get(position).getLongitud().toString());
holder.foto.setImageBitmap(newbitMap);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
//This returns 0 always
convertView=inflater.inflate(R.layout.foto_layout, null);
holder=new ViewHolder();
holder.lat=(TextView)convertView.findViewById(R.id.textlat);
holder.lon=(TextView)convertView.findViewById(R.id.textlon);
holder.foto=(ImageView)convertView.findViewById(R.id.foto);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
int bmWidth=fotos.get(position).getFoto().getWidth();
int bmHeight=fotos.get(position).getFoto().getHeight();
int ivWidth;
int ivHeigth;
int new_width;
int new_height;
ivWidth=dpToPx(80);
ivHeigth=dpToPx(80);
new_width=ivWidth;
new_height = (int) Math.floor((double) bmHeight *( (double) new_width / (double) bmWidth));
Bitmap newbitMap = Bitmap.createScaledBitmap(fotos.get(position).getFoto(), new_width, new_height, true);
holder.lat.setText(fotos.get(position).getLatitud().toString());
holder.lon.setText(fotos.get(position).getLongitud().toString());
holder.foto.setImageBitmap(newbitMap);
return convertView;
}

GridView with equal rows

I have a gridview with 2 rows and 3 columns. Want to make the rows streched equally across the screen without having the user screen to see any of the rows. The rows should be of equal height (preferrably, the height of the gridview / 3).
Currently using this adapter:
public class HomeAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
private Context mContext;
private int h;
public HomeAdapter(Context context, int height) {
mContext = context;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
h = height;
}
#Override
public int getCount() {
return 6;
}
#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) {
FunctionHolder holder;
if (convertView == null) {
holder = new FunctionHolder();
convertView = mLayoutInflater.inflate(R.layout.view_flipper, parent, false);
holder.flipper = (ViewFlipper) convertView.findViewById(R.id.flipper);
} else {
holder = (FunctionHolder) convertView.getTag();
}
View topView = mLayoutInflater.inflate(R.layout.first_item, null);
View bottomView = mLayoutInflater.inflate(R.layout.second_item, null);
changeView(bottomView, position);
changeView(topView, position);
holder.flipper.addView(topView, 0);
holder.flipper.addView(bottomView, 1);
startAnimation(holder.flipper, position);
convertView.setMinimumHeight(h);
convertView.setTag(holder);
return convertView;
}
gridview.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView
android:drawSelectorOnTop="true"
android:listSelector="#drawable/list_bg"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:padding="5dp"
android:columnWidth="100dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:gravity="center"
android:id="#+id/home_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"></GridView>
Try this
public static int getScreenHeight(Context c) {
if (screenHeight == 0) {
WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenHeight = size.y;
}
return screenHeight;
}
Then set GridView item's height dynamically depending on height of device
v.getLayoutParams().height = getScreenHeight(context)/3;

Unable to view images properly in a GridView

MainActivity:
public class AndroidCustomGalleryActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_custom_gallery);
getFromSdcard();
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
}
public void getFromSdcard()
{
File file= new File(android.os.Environment.getExternalStorageDirectory(),"SnapBoard");
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
f.add(listFile[i].getAbsolutePath());
}
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return f.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));
holder.imageview.setImageBitmap(myBitmap);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<GridView
android:id="#+id/PhoneImageGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</RelativeLayout>
GalleryItem.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/thumbImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<CheckBox
android:id="#+id/itemCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
SnapShot:
I am able to retrieve the images from a seperate folder from my SD card and display it in a grid view but the view seems rather collapsed. Does it has something to do with screen size ? I am using a Galaxy ACE DUOS (3.5 inch). Will try to post the screen shot shortly. Help will be much appreciated. Thanks in advance.
EDIT:
Logcat:
12-19 11:08:25.335: D/dalvikvm(22171): GC_EXTERNAL_ALLOC freed 66K, 47% free 2957K/5511K, external 58486K/58486K, paused 39ms
12-19 11:08:25.351: E/dalvikvm-heap(22171): 9830400-byte external allocation too large for this process.
12-19 11:08:25.390: E/GraphicsJNI(22171): VM won't let us allocate 9830400 bytes
12-19 11:08:25.390: D/dalvikvm(22171): GC_FOR_MALLOC freed <1K, 47% free 2957K/5511K, external 58486K/58486K, paused 30ms
12-19 11:08:25.390: D/skia(22171): --- decoder->decode returned false
Instead of using a seperate imageview in your inflator what you have to do is remove imageview from inflator and set your thnumbnail as a background for your inflator relativewlayout.
I think so your problem is when ur are getting the view of grid view there is mistake.
Error
public Object getItem(int position) {
return position;
}
Correction
public Object getItem(int position) {
return f.get(position);
}
The error is because whenever you display image, you allocate the image size in Virtual memory. This can be overridden by resizing the bitmap and reducing the size and then display the image.
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
In your Code
Bitmap myresizedbitmap= getResizedBitmap(myBitmap,300, 300);
holder.imageview.setImageBitmap(myresizedbitmap);

Android gridview streachmode="columnWidth", set the item content to fit in the view

I have a GridView with the following properties:
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/PhoneImageGrid"
style="#style/PhotoGridLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:alwaysDrawnWithCache="true"
android:clipChildren="true"
android:columnWidth="100dp"
android:horizontalSpacing="2dp"
android:numColumns="auto_fit"
android:padding="4dp"
android:scrollbars="none"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:stretchMode="columnWidth"
android:verticalSpacing="4dp" />
Here is the grid item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/thumbImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<CheckBox
android:id="#+id/itemCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Now when when i run the app, i got a gridview, looks everything right in portrait and when i turn it to landscape the col width is being changed but i want the contents of the item also to be scaled proportionately according to the new col width(item_height = item_width = new col width). How can i achieve this? Thanks
Its bit tricky to set get the gridview col width. One you got the col width you can set the imageview height to the col width and notify adapter of changes. (code taken from the android samples: https://developer.android.com/training/displaying-bitmaps/index.html)
Here's the way to measure the col width:
imagegrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(imagegrid.getWidth()
/ (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
final int columnWidth = (imagegrid.getWidth() / numColumns) - mImageThumbSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
Create these methods in the Adapter:
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
// mImageFetcher.setImageSize(height);
notifyDataSetChanged();
}
Set the initial image size as:
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
Here's the complete adapter class:
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemHeight = 0;
private int mNumColumns = 0;
private RelativeLayout.LayoutParams mImageViewLayoutParams;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
}
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
// mImageFetcher.setImageSize(height);
notifyDataSetChanged();
}
public int getCount() {
return images.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ImageItem item = images.get(position);
holder.imageview.setId(position);
// holder.imageview.setImageBitmap(item.img);
holder.imageview.setLayoutParams(mImageViewLayoutParams);
// Check the height matches our calculated column width
if (holder.imageview.getLayoutParams().height != mItemHeight) {
holder.imageview.setLayoutParams(mImageViewLayoutParams);
}
holder.imageview.setImageBitmap(item.img);
holder.checkbox.setChecked(item.selection);
return convertView;
}
}

Categories

Resources