I am able to manage the horizontal space between images in a grid view. But how to reduce vertical space between images in a grid view.
Following is my code:
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_margin="5dp">
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:clipChildren="true"
android:alwaysDrawnWithCache="true"
android:numColumns="auto_fit"
android:columnWidth="70dp">
</GridView>
</LinearLayout>
getView method
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = null;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imageView.setTag(position);
} else {
imageView = (ImageView) convertView;
}
if((Integer)imageView.getTag() == 0) {
Bitmap bitmap = Bitmap.createScaledBitmap(imgPic.get(position).getBitmap(), 250, 200, false);
imageView.setImageBitmap(bitmap);
}else {
FileInputStream fs = null;
//Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).getFilePath().toString()));
if(fs!=null) {
//to get the thumbnail view of the image
Bitmap scaledBitmap = decodeFile(imgPic.get(position).getFilePath().toString(), 250, 200);
imageView.setImageBitmap(scaledBitmap);
imageView.setId(position);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return imageView;
}
decodeFile is a function to resize the image
You use the attribute android:horizontalSpacing="5dp", decreased its value.
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'm having a problem of displaying ImageViews with the correct size. Almost all the posts that I've read through involves ImageViews that are created in the layout file. However in my case, I'm creating ImageViews programmatically.
I'm trying to display all images from a particular folder located in the storage. The bitmaps retrieved will be placed in ImageViews which are contained within a GridView.
Here's my code:
//pass an array containing all images paths to adapter
imageGrid.setAdapter(new GridViewAdapter(getActivity(), FilePathStrings));
part of GridVewAdapter code:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(5, 5, 5, 5);
imageView.setAdjustViewBounds(true);
}else{
imageView = (ImageView) convertView;
}
imageView.setTag(filepath[position]);
new LoadImages(imageView).execute();
return imageView;
}
AsyncTask to retrieve bitmaps:
private class LoadImages extends AsyncTask<Object, Void, Bitmap> {
private ImageView imgView;
private String path;
private LoadImages(ImageView imgView) {
this.imgView = imgView;
this.path = imgView.getTag().toString();
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = 6;
bitmap = BitmapFactory.decodeFile(path, bmOptions);
try {
int dimension = getSquareCropDimensionForBitmap(bitmap);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
}catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (!imgView.getTag().toString().equals(path)) {
return;
}
if(result != null && imgView != null){
imgView.setVisibility(View.VISIBLE);
imgView.setImageBitmap(result);
}else{
imgView.setVisibility(View.GONE);
}
}
}
Method to get equal dimensions so bitmaps will be displayed as squares:
private int getSquareCropDimensionForBitmap(Bitmap bitmap) {
int dimension;
//If the bitmap is wider than it is height then use the height as the square crop dimension
if (bitmap.getWidth() >= bitmap.getHeight()) {
dimension = bitmap.getHeight();
}
//If the bitmap is taller than it is width use the width as the square crop dimension
else {
dimension = bitmap.getWidth();
}
return dimension;
}
GridView in the layout file:
<GridView
android:id="#+id/imageGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="30dp"
android:numColumns="5"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:layout_marginTop="30dp">
</GridView>
The result that I've gotten:
The circled thin "lines" are actually the ImageViews displayed.
Any help is very much appreciated. Thank you in advance!
<GridView
android:id="#+id/imageGridView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:layout_marginTop="30dp">
I have other views above the GridView so I can't set its height to fill_parent/match_parent in the .xml file as it will affect the views above.
The solution to my problem is to set GridView's height and width programmatically.
Replace:
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
With this:
imageView.setLayoutParams(new GridView.LayoutParams(int height, int width));
Explanation:
Grid View doc
Anyone who has a better answer, please post it :)
I currently working on a Drag 'n' Drop application.
My app has 2 layouts.
The 1st layout is 2 balls (Images) of different color.
The 2nd layout is 3 balls (Images) of different color.
When the user drags one ball onto any layout & drops that ball onto the other layout, the app then checks if a ball with the same color is in this layout: if so, it then removes those 2 balls, otherwise adds the ball to that layout.
My XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="#+id/relative">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="150sp"
android:background="#00FF00"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ball_red" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ball_blue" />
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ball_pink" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/linearLayout1"
android:layout_centerHorizontal="true"
android:background="#0F0F0F">
<ImageView
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#drawable/ball_red" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#drawable/ball_yellow" />
</LinearLayout>
</RelativeLayout>
My Activity Class
public class MainActivity extends Activity implements OnTouchListener, OnDragListener{
ImageView i1,i2,i3,i4,i5,i6;
Drawable d1,d2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i1=(ImageView) findViewById(R.id.imageView1); i2=(ImageView) findViewById(R.id.imageView2);
i5=(ImageView) findViewById(R.id.imageView5); i6=(ImageView) findViewById(R.id.imageView6); i4=(ImageView) findViewById(R.id.imageView4);
findViewById(R.id.linearLayout1).setOnDragListener(this);
findViewById(R.id.linearLayout2).setOnDragListener(this);
i6.setOnTouchListener(this); i5.setOnTouchListener(this); i2.setOnTouchListener(this); i1.setOnTouchListener(this);
i4.setOnTouchListener(this);
d1=i1.getDrawable(); d2=i6.getDrawable();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(null, shadowBuilder, v, 0);
v.setVisibility(View.VISIBLE);
return true;
}
else {
return false;
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
public boolean onDrag(View v, DragEvent e) {
// TODO Auto-generated method stub
if (e.getAction()==DragEvent.ACTION_DROP) {
View view = (View) e.getLocalState();
ViewGroup from = (ViewGroup) view.getParent();
from.removeView(view);
LinearLayout to = (LinearLayout) v;
boolean comp=false;
comp=compareDrawable(d1, d2);;
if(comp == false)
{
to.addView(view);
view.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Add.", Toast.LENGTH_LONG ).show();
}
else
{
to.removeView(view);
from.addView(view);
view.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "Remove.", Toast.LENGTH_LONG ).show();
}
}
return true;
}
public boolean compareDrawable(Drawable d1, Drawable d2){
try{
Bitmap bitmap1 = ((BitmapDrawable)d1).getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
stream1.flush();
byte[] bitmapdata1 = stream1.toByteArray();
stream1.close();
Bitmap bitmap2 = ((BitmapDrawable)d2).getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, stream2);
stream2.flush();
byte[] bitmapdata2 = stream2.toByteArray();
stream2.close();
return bitmapdata1.equals(bitmapdata2);
}
catch (Exception e) {
// TODO: handle exception
}
return false;
}
}
Get the 2 images ID then compare it,
if(img1.getId()==img2.getId())
{
//Your stuff
}
or try this
Bitmap bitmap = ((BitmapDrawable)img1).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable)img2).getBitmap();
if(bitmap == bitmap2)
{
//Code blcok
}
I believe that what you actually need is to compare if two bitmaps are the same content.
For this you must use Bitmap.sameAs(Bitmap) look at it here
As an advice don't compare objects with "==" but using equals!
PS : sameAs method is starting from API 12
can we use two gridview in a single xml file.it display onle first gridview.. how can i use two gridview together.i want to display pics from drawable folder in first gridview & from url in second gridview. pls guide me..
this is gridview.xml--
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<GridView
android:id="#+id/gridview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="1dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" >
</GridView>
</LinearLayout>
this is imageadapter class which display pic in gridview.
public class image extends BaseAdapter {
private Context c;
int h = 0;
public Integer[] pic = { R.drawable.i1, R.drawable.i2, R.drawable.i3,
R.drawable.i4, R.drawable.i5, R.drawable.i6 };
public final static String[] imageThumbUrls = new String[] {
"https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s160-c/A%252520Photographer.jpg","https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s160-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg", "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s160-c/Another%252520Rockaway%252520Sunset.jpg","https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s160-c/Antelope%252520Butte.jpg", "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s160-c/Antelope%252520Hallway.jpg","https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s160-c/Antelope%252520Walls.jpg", "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s160-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg","https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s160-c/Backlit%252520Cloud.jpg", "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s160-c/Bee%252520and%252520Flower.jpg","https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s160-c/Bonzai%252520Rock%252520Sunset.jpg","https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s160-c/Caterpillar.jpg","https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s160-c/Chess.jpg","https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s160-c/Chihuly.jpg","https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s160-c/Closed%252520Door.jpg","https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s160-c/Colorado%252520River%252520Sunset.jpg","https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s160-c/Colors%252520of%252520Autumn.jpg", "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s160-c/Countryside.jpg","https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s160-c/Death%252520Valley%252520-%252520Dunes.jpg","https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s160-c/Delicate%252520Arch.jpg", "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s160-c/Despair.jpg", "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s160-c/Eagle%252520Fall%252520Sunrise.jpg"};
public image(Context c1) {
Log.i("iamgeclass", "create");
c = c1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pic.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return pic[arg0];
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int pos, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView i;
i = new ImageView(c);
i.setLayoutParams(new GridView.LayoutParams(85, 85));
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
i.setPadding(8, 8, 8, 8);
i.setImageResource(pic[pos]);
ImageLoader ps = new ImageLoader(c);
ps.DisplayImage(imageThumbUrls[pos], i);
return i;
}
}
this is imageloader class which use to display pic from url.
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
int stub_id = R.drawable.ic_launcher;
public void DisplayImage(String url,ImageView imageView)
{
//stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
// imageView.setImageResource(loader);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
#Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
can anyone tell me where is the mistake..thanks
Right now I can only see a single GridView in your layout, if you want it side by side do something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="0.5" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:columnWidth="80dp"
android:descendantFocusability="afterDescendants"
android:focusable="true"
android:gravity="bottom"
android:horizontalSpacing="3dp"
android:numColumns="5"
android:stretchMode="columnWidth"
android:verticalSpacing="3dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
android:gravity="center"
android:orientation="vertical"
android:layout_weight="0.5" >
<GridView
android:id="#+id/gridview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:columnWidth="80dp"
android:descendantFocusability="afterDescendants"
android:focusable="true"
android:gravity="bottom"
android:horizontalSpacing="3dp"
android:numColumns="5"
android:stretchMode="columnWidth"
android:verticalSpacing="3dp" />
</LinearLayout>
</LinearLayout>
Then just set two different adapters or two instances of the same adapter to each GridView. Please further explain your problem if i missed anything.
I assigned the adapters like this: (You need two different adapters or check the id of each gridview inside the adapter)
gridview2 = (GridView) findViewById(R.id.gridview2);
gridview2.setAdapter(new ImageAdapter(this));
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
I don't think what you are trying to achieve is possible.
You could try any of the below approach:
Use a Single GridView. Load the image URI from drawable folder and also the images from URL into an arraylist and setup the adapter and hence the GridView.
If you need two gridViews in a Single Activity, Create Two fragments with gridView in each layout. Load the drawable images in one gridView of "fragment A" and Url images in "fragment B". And In the FragmentActivity's layout, just include both fragments.
I have a GridView that I am using to display a row of 4 images, each image is 200 x 200 pixels. Here is the layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<GridView
android:id="#+id/myGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:numColumns="4" >
</GridView>
</RelativeLayout>
When I run my app here is what the images look like:
As you can see the images are getting scaled (narrowed) to fit the screen.
How do I make it so the images are stretched both vertically and horizontally to maintain the correct aspect ratio?
Note that I am using an adapter to draw the images:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(imageIds[position]);
return imageView;
}
I got the same issue in last weak.Use my image view class and solve this issue.
public class iv_autoSizedImageView extends ImageView {
public iv_autoSizedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
try {
getLayoutParams().height = getMeasuredWidth();
} catch (Exception e) {
// TODO: handle exception
}
}
}
layout.xml
<com.sample.test.iv_autoSizedImageView
android:id="#+id/IV_NEWS_IMAGE"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>