Unable to view images properly in a GridView - android

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);

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"/>

Can't resize image in android without loosing content

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"
/>

How to add TextView inside a GridView filled with ImageView

I have a GridView where I add images directly with ImageView (I don't use an XML for the image). Now, I want to add image name at the bottom of each cell using a TextView. How can I do it? Thanks in advance.
Custom Adapter Class:
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
private GridView imageCarrete;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth, GridView imageCarrete) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
this.imageCarrete = imageCarrete;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// Listener del GridView
imageCarrete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", position);
_activity.startActivityForResult(i, 1234);
}
});
return imageView;
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public void remove(String path){
_filePaths.remove(path);
}
}
GridView XML
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000">
</GridView>
Within your getView() method, replace your ImageView with a TextView with a drawable:
TextView tv = new TextView(context);
tv.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
you will supply the drawable to the top and 0 to the rest, ie:
tv.setCompoundDrawablesWithIntrinsicBounds(0, yourDrawable, 0, 0);
Just create a LinearLayout as you are creating Imagview in getView() method... add ImageView and TextView to it with addView() method.... have a look ..
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout _ll;
if (convertView == null) {
_ll = new LinearLayout(mContext);
_ll.setOrientation(LinearLayout.VERTICAL);
ImageView img = new ImageView(mContext);
img.setLayoutParams(new LinearLayout.LayoutParams(100, 100)); // your image size
img.setBackgroundResource(images[position]); // here pass your array list position
_ll.addView(img);
TextView text = new TextView(mContext);
text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
text.setText("dsaf");
text.setGravity(Gravity.CENTER);
_ll.addView(text);
} else {
_ll = (LinearLayout) convertView;
}
return _ll;
}
You can also use RelativeLayout if you want to overlay your text over image..

How to get Image(bitmap) from gridView

I have gridView that load images from sdcard/dcim/camera and shows them.
I want to put onclick listener on images and when I click on one it shoudl open that picture in other activity. How can I get image from gridView when I click on it.
error is on this line:
intent.putExtra("image", item.getImage());
how can I fix this or how else can I make it work ?
public class MainActivity extends Activity {
ImageAdapter myImageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridView);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.putExtra("image", item.getImage()); // ERROR IS ON ITEM.GETIMAGE
//Start details activity
startActivity(intent);
}
});
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera/";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
myImageAdapter.add(file.getAbsolutePath());
}
}
}
//*****************************************/
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap image ) {
super();
this.image = image;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
//****************************************************/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path){
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
//***********************************************/
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_activity);
Bitmap bitmap = getIntent().getParcelableExtra("image");
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageBitmap(bitmap);
}
}
//*******************************************************/
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0">
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="150dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
</RelativeLayout>
//*************************************************/
details_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000">
<ImageView
android:id="#+id/image1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitCenter" />
</FrameLayout>
It is bad practice to pass bitmaps between activities.
The logical thing to do would be to pass the image path to the next activity and then decode the image in that activity based on the image view dimensions.
I hope this was helpful. :)

Android: first element of a GridView is misplaced in galaxy S3 and S4

I'm building an app that has a mini slotMachine game inside. The problem is that I use a GridView for each column of the slot and for some devices (not all) the first symbol of the slot has a space above that comes from nowhere...
The table of the slot is 3 rows X 5 columns.
The space doesn't come from the calculation of the symbol width and height because I've found that with two devices withe perfectly identical resolution and density (Galaxy tab 10.1 and Galaxy note 10.1) the spacing is different: 0 for one and 5 for the other.
Any help?
My MainActivity:
public class MainActivity extends Activity{
SlotView slot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slot=new SlotView(this);
slot.refreshSlotView("AAAAAAAAAAAAAAA");
}
}
SlotView:
public class SlotView {
private ArrayList<GridAdapter> adapter=new ArrayList<GridAdapter>();
public float H_RATIO=2/3; //height ratio of the grid based on the device
public float W_RATIO=5/6; //width ratio of the grid based on the device
Activity activity;
String path = "file:///android_asset/Slot/Slot-";
public SlotView(Context c){
activity = (Activity) c;
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
final int hDisplay=dm.heightPixels;
int wImage=(1024*hDisplay)/768; //width of the central image
float heightGrid=(hDisplay*2)/3; //grid height
float widthGrid=((wImage*5)/6); //grid width
float heightSymbol=(heightGrid-(8))/3; // symbol height (3 symbols for column with a spacing of 4 px)
//relative layout for the container table
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams((int)widthGrid, (int)heightGrid);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
// grid of the slot
LinearLayout grid_layout=(LinearLayout)activity.findViewById(R.id.layout_grid);
grid_layout.setLayoutParams(params);
grid_layout.setGravity(Gravity.TOP);
// gridview of the columns
LinearLayout.LayoutParams params_grid=new LinearLayout.LayoutParams((int)heightSymbol, (int)heightGrid);
for(int i=0; i<5; i++){ // five columns
GridView slot=new GridView(activity);
slot.setScrollContainer(false);
slot.setVerticalScrollBarEnabled(false);
slot.setHorizontalScrollBarEnabled(false);
if(i<4) {
params_grid.setMargins(0,0,4,0); // spacing between each column
}
slot.setLayoutParams(params_grid);
slot.setVerticalSpacing(4);
slot.setPadding(0, 0, 0, 0);
slot.setColumnWidth((int)heightSymbol);
slot.setNumColumns(GridView.AUTO_FIT);
slot.setGravity(Gravity.CENTER);
GridAdapter grid_adapter=new GridAdapter(activity, (int)heightSymbol, (int)heightSymbol);
adapter.add(grid_adapter);
slot.setAdapter(grid_adapter);
grid_layout.addView(slot);
}
}
public void refreshSlotView(String configTris){
for(int pos=0; pos<5; pos++){
String[] mThumbIds=new String[3];
int z=0;
for(int i=pos; z<3 && i<configTris.length(); i=i+5){
char letter=configTris.charAt(i);
mThumbIds[z]=path + letter + ".png";
z++;
}
adapter.get(pos).setArrayOfImage(mThumbIds);
adapter.get(pos).notifyDataSetChanged();
}
}
}
The adapter:
public class GridAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds={};
private int w;
private int h;
public GridAdapter(Context c, int w, int h) {
mContext = c;
this.w=w;
this.h=h;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
ImageView imageView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.slot_element, null);
RelativeLayout rel=(RelativeLayout)view.findViewById(R.id.rel);
rel.setLayoutParams(new GridView.LayoutParams(w, h));
imageView=(ImageView)view.findViewById(R.id.image);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(w, h);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(params);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}else{
imageView = (ImageView) view.findViewById(R.id.image);
}
Picasso.with(mContext).load(mThumbIds[position]).into(imageView); // puts the image in the imageview
return view;
}
public void setArrayOfImage(String[] images){
this.mThumbIds=images;
}
public void showSymbolAtIndex(char letter, int position){
mThumbIds[position]="file:///android_asset/" + "Slot/Slot-" + letter + ".png";
notifyDataSetChanged();
}
}
This is the MainActivity Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/layout_grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
And the slot_element Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rel"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
</RelativeLayout>
Now that's the result:
And that's the proof of the existing spacing (if I drag one of the columns up):

Categories

Resources