I am trying to set a 3:2 ratio for a gridview (IE 300 pixels by 200 per cell). Here is my image adapter:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
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(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.image1, R.drawable.image2, R.drawable.image3,
};
}
I've tried adjusting the imageView.setLayoutParams(new GridView.LayoutParams(200, 200)); width parameter to 300 but it results in overlapping. Here is my XML File:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Weird overlapping:
Hi there you can try like this from your Activity :
ViewGroup.LayoutParams layoutParams = gridview.getLayoutParams();
layoutParams.height = 200;
layoutParams.width = 300;
gridview.setLayoutParams(layoutParams);
or
int final width = 300;
int final height = 200;
ViewGroup.LayoutParams lauoutParams = new ViewGroup.LayoutParams(width,height);
gridView.setLayoutParams(lp);
This might help.
Discovered this library: AsymetricGridView
Related
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"
/>
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..
I want to create 3x3 gridview programmatically for displaying images. And I want to set each item height and width by getting screen dimensions. Like:
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Then each item width = screenWidth/3;
Please someone help me or some link for reference.
This is how you can create gridview programmatically,
GridView grid = new GridView(this);
grid.setId(ViewIdentification.getId());
grid.setLayoutParams(new GridView.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
grid.setBackgroundColor(Color.WHITE);
grid.setNumColumns(3);
grid.setColumnWidth(GridView.AUTO_FIT);
grid.setVerticalSpacing(5);
grid.setHorizontalSpacing(5);
grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
Add the above view to your layout. And here you can get the height and width of the display.
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay()
.getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
And here is the adapter class :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Bitmap[]mis_fotos;
public ImageAdapter(Context c) {
mContext = c; }
public int getCount() {
return mis_fotos.length;
}
public Object getItem(int position) {
return position; }
public long getItemId(int position) {
return 0; }
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(width/3, height/3));
imageView.setScaleType(ImageView.setScaleType(ScaleType.FIT_XY));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(mis_fotos[position]);
return imageView;
}
}
Then, It's upto you, If you are passing dynamic URL, change your adapter accordingly.
set your adapter to your gridview.
Let me know if you have any issues.
In your Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GridView gridView = new GridView(this);
gridView.setNumColumns(3);
setContentView(gridView);
gridView.setAdapter(new GridViewAdapter(this));
}
And Adapter:
private class GridViewAdapter extends BaseAdapter {
private Context context;
private final int length = 9;
public GridViewAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels / 3;
int height = metrics.heightPixels / 3;
imageView.setLayoutParams(new GridView.LayoutParams(width, height));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
}
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):
I follow this guide to insert images in a gallery using grid view: http://developer.android.com/guide/topics/ui/layout/gridview.html
I edited the imageadapter code as follow:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
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.setId(R.id.img_gallery);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private int[] mThumbIds = {R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1, R.drawable.itinerario1_1};
}
and this is img_gallery xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/img_gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:adjustViewBounds="true"/>
and this is the main layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:fadingEdge="none">
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"
android:gravity="center"
android:padding="5dp"
/>
the problem is that when i tun the app, imageview has a lot of top and bottom padding. I also tried to set it to 0 in the xml but it doesn't change.
You are setting the padding on runtime-
remove this line-
imageView.setPadding(8, 8, 8, 8);
imageView.setPadding(0, 0, 0, 0); in Base Adapter.
The xml file loads first, than the adapter. That means that if you set the padding to 0 in your xml, they will still be overriden from your adapter class. Try setting them to 0, or better yet, remove that line completely. It should work.