Android-GridView Padding problem - android

Im working on a app where im loading an image into the GridView... My problem now is
when im using the imageView.setPadding(10,10,10,10) its working fine for HTC Hero but in case of Motorola Droid they are overlapping each other...
How to make the padding to be common for all mobile...
Here is my code..
package com.android.sampleDesign1;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class TicTacToeAdapter extends BaseAdapter {
public ImageView imageView;
private Context mContext;
private Integer mThumbIds = R.drawable.images;
private Integer image;
public TicTacToeAdapter(Context c) {
mContext = c;
}
public int getCount() {
return 9;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
image = mThumbIds;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(image);
imageView.setPadding(10,10,10,10);
} else {
imageView = (ImageView) convertView;
imageView.setImageResource(image);
}
return imageView;
}
}
I have also tried to use the
int w = gridView.getWidth();
int myViewWidth = Math.round(W * .12f);
and also i tried with the
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);
So is there anyother way to do.. Or am i wrong anywhere..
Help me out..
Thanks in advance.

Rather defining the padding in pixels, you need to define it in dips (density independent pixels) and then convert the dips to pixels at run time.
So you would need to do something similar to
private static final float PADDING_IN_DP = 10.0f; // 1 dip = 1 pixel on an MDPI device
private final int mPaddingInPixels;
public TicTacToeAdapter(Context context) {
....
// Convert the dps to pixels
final float scale = context.getResources().getDisplayMetrics().density;
mPaddingInPixels = (int) (PADDING_IN_DP * scale + 0.5f);
}
...
public View getView(int position, View convertView, ViewGroup parent) {
...
if (convertView == null) {
...
imageView.setPadding(mPaddingInPixels, mPaddingInPixels, mPaddingInPixels, mPaddingInPixels);
}
...
}
...
The scale you get in your constructor will differ depending on the density of the screen of the device your app is running on.
(Note: dip and dp are the same thing)

Related

Why am I getting "cannot resolve symbol urlDrawable" in this class

I'm trying to display <img> tags in json string and I using the accepted answer in this question but Android Studio is complaining "cannot resolve symbol urlDrawable
Please can anybody tell me why this is happening and how to fix it?
UILImageGetter
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.View;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
urlDrawable;
public UILImageGetter(View textView, Context context) {
this.c = context;
this.conatiner = (TextView) textView;
}
#Override
public Drawable getDrawable(String source) {
urlDrawable = new UrlImageDownloader(c.getResources(), source);
urlDrawable.drawable = c.getResources().getDrawable(R.drawable.default_thumb);
ImageLoader.getInstance().loadImage(source, new SimpleListener(urlDrawable));
return urlDrawable;
}
private class SimpleListener extends SimpleImageLoadingListener {
UrlImageDownloader mUrlImageDownloader;
public SimpleListener(UrlImageDownloader downloader) {
super();
mUrlImageDownloader= downloader;
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
int width = loadedImage.getWidth();
int height = loadedImage.getHeight();
int newWidth = width;
int newHeight = height;
if (width > conatiner.getWidth()) {
newWidth = conatiner.getWidth();
newHeight = (newWidth * height) / width;
}
if (view != null) {
view.getLayoutParams().width = newWidth;
view.getLayoutParams().height = newHeight;
}
Drawable result = new BitmapDrawable(c.getResources(), loadedImage);
result.setBounds(0, 0, newWidth, newHeight);
mUrlImageDownloader.setBounds(0, 0, newWidth, newHeight);
mUrlImageDownloader.mDrawable = result;
conatiner.setHeight((conatiner.getHeight() + result.getIntrinsicHeight()));
conatiner.invalidate();
}
}
private class UrlImageDownloader extends BitmapDrawable {
public Drawable mDrawable;
public UrlImageDownloader(Resources resources, String filepath) {
super(resources, filepath);
mDrawable = new BitmapDrawable(resources, filepath);
}
#Override
public void draw(Canvas canvas) {
if (mDrawable != null) {
mDrawable.draw(canvas);
}
}
}
}
You haven't assigned a type to urlDrawable;
This portion of code contains the error:
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
urlDrawable;
Try this:
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
UrlImageDownloader urlDrawable;
Java is a strongly typed language, which means that all variables must be declared as being of some type.
Since you don't specify a type for urlDrawable, the compiler doesn't understand that you're declaring a variable.
Simply replace
urlDrawable;
with
UrlImageDownloader urlDrawable;

I want to set images into into gridview from SD card?

Below is my AppConstant.java
package com.domore.gridviewtutorial.helper;
import java.util.Arrays;
import java.util.List;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class AppContant {
// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;
// Gridview image padding
public static final int GRID_PADDING = 8; // in dp
// SD card image directory
public static final String PHOTO_ALBUM = "MyPhotos";
// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
"png");
}
in this class i set the file extension which i load in my app
Here, is my utils class
package com.domore.gridviewtutorial.helper;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class Utils {
private Context context;
public Utils(Context context){
this.context=context;
}
public ArrayList<String> getFilePaths(){
ArrayList<String> filePaths=new ArrayList<String>();
File directory=new File(android.os.Environment.getExternalStorageDirectory()+File.separator+AppContant.PHOTO_ALBUM);
if(directory.isDirectory()){
File[] listFiles=directory.listFiles();
if(listFiles.length > 0 ){
for(int i=0;i<listFiles.length;i++){
String filePath=listFiles[i].getAbsolutePath();
if(IsSupportedFile(filePath)){
filePaths.add(filePath);
}
}
}
else{
Toast.makeText(
context,
AppContant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
}
else{
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Error!");
alert.setMessage(AppContant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppContant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
Here is my grid_layout.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>
i have Adapter class to load images
package com.domore.gridviewtutorial.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.GridView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.view.View.OnClickListener;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> _filePaths=new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity,ArrayList<String> _filePaths,int imageWidth){
this.activity=activity;
this._filePaths=_filePaths;
this.imageWidth=imageWidth;
}
#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(this.activity);
}
else{
imageView=(ImageView)convertView;
}
Bitmap image=decodeFile(this._filePaths.get(position),imageWidth,imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Intent i = new Intent(activity, FullScreenViewActivity.class);
// i.putExtra("position", _postion);
// activity.startActivity(i);
}
}
/*
* 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;
}
}
Here is my MainActivity.java
package com.domore.gridviewtutorial;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.GridLayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.domore.gridviewtutorial.adapter.GridViewImageAdapter;
import com.domore.gridviewtutorial.helper.AppContant;
import com.domore.gridviewtutorial.helper.Utils;
import java.util.ArrayList;
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
I got error in mainActivity.java
here is my error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setNumColumns(int)' on a null object reference
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.InitilizeGridLayout(AndroidGridLayoutActivity.java:46)
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:34)
can anyone who help me to solve out this error i cannot able to understand.
Your gridView variable is null because you are recreating the a new variable gridView in your onCreate() method and your's activity's instance gridView variable is never get Initialized.
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// initiated the gridView variable
gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}

GridView bitmap images double upon refresh

I was following this Android tutorial to fix an "out of memory" error I kept getting when using Bitmap images in my GridView. The tutorial fixed this problem, but now when I click on other tabs in my activity, then return to my photo tab, the photos that are there, double. So for example, when I first load the tab, it pulls 3 photos from my SD card, and fills the rest with placeholder images. But then when I browse other tabs (4 altogether), I come back to find 6 images in my photo tab GridView, and the rest are placeholders.
Background info: each time my tab is visible, it loads images from the SD card, changes them into bitmaps, then my adapter puts those into each ImageView inside the GridView. Before I had the memory problem, it loaded fine, and did not double the images when I browsed other tabs then came back to the photo tab. It did however eventually crash with the memory problem, so I had to fix that.
How can I not load double upon a refresh to tab? Thanks for your help.
PhotoTab.java
package org.azurespot.cutecollection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import org.azurespot.R;
import java.io.File;
import java.util.ArrayList;
/**
* Created by mizu on 2/8/15.
*/
public class PhotoTab extends Fragment {
private GridView gridView;
File[] files;
ArrayList<PhotoGridItem> photoList = new ArrayList<>();
ArrayAdapter<PhotoGridItem> adapter;
Bitmap bitmap;
public PhotoTab() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.photo_tab, container, false);
// with fragments, make sure you include the rootView when finding id
gridView = (GridView) v.findViewById(R.id.photo_grid);
adapter = new GridViewPhotoAdapter(getActivity(), R.layout.photo_grid_item);
// Set the Adapter to GridView
gridView.setAdapter(adapter);
adapter.addAll(loadSDCard());
// add the default icons remaining, to GridView, if less than 24 files on SD card
for (int i = 0; i < (24 - photoList.size()); i++) {
adapter.add(new PhotoGridItem(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_photo_placeholder)));
}
adapter.notifyDataSetChanged();
return v;
}
private ArrayList<PhotoGridItem> loadSDCard() {
try {
// gets directory CutePhotos from sd card
File cutePhotosDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES), "CutePhotos");
// lists all files in CutePhotos, loads in Files[] array
files = cutePhotosDir.listFiles();
for (File singleFile : files) {
String filePath = singleFile.getAbsolutePath();
bitmap = decodeSampledBitmap(filePath, 270, 270);
photoList.add(new PhotoGridItem(bitmap));
}
} catch (Exception e) {
e.printStackTrace();
}
return photoList;
}
public static 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) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmap(String path, int reqWidth, int reqHeight) {
// 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;
return BitmapFactory.decodeFile(path, options);
}
}
GridViewPhotoAdapter
package org.azurespot.cutecollection;
/**
* Created by mizu on 2/5/15.
*/
// package org.azurespot.cutecollection;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.azurespot.R;
/**
* Created by mizu on 2/5/15.
*/
public class GridViewPhotoAdapter extends ArrayAdapter<PhotoGridItem> {
public Context context;
private int resourceId;
Bitmap bm;
public GridViewPhotoAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
this.context = context;
this.resourceId = layoutResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.photo_grid_view);
// stores holder with view
row.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
PhotoGridItem photoGridItem = getItem(position);
if (photoGridItem != null) {
bm = photoGridItem.getImage();
holder.imageView.setImageBitmap(bm);
// positioning the image in the GridView slot
holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.imageView.setLayoutParams(new LinearLayout.LayoutParams
(270, 270));
}
return row;
}
public class ViewHolder{
ImageView imageView;
}
}
Try this:
adap = null;
if (adap == null) {
adap = new Grid_View_Adatper(activity, arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();

GridView not displaying correct thumbnail

I have a folder on my SDCard that is hidden with the .nomedia. I have this Imageadapter that displays the contents of the folder (Images and Videos) in a GridView. They all seem to show up, but sometimes when I click on a thumbnail that I know is a Video, an image is displayed or even a different video. Can someone please tell me where I am going wrong with this?
GridViewImageAdapter.class
package com.soboapps.todos.adapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class GridViewImageAdapter extends BaseAdapter {
private Activity mActivity;
private ArrayList<String> mFilePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths, int imageWidth) {
this.mActivity = activity;
this.mFilePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.mFilePaths.size();
}
#Override
public Object getItem(int position) {
return this.mFilePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mActivity);
if(mFilePaths.get(position).contains("jpg") || mFilePaths.get(position).contains("jpeg") ||
mFilePaths.get(position).contains("png"))
{
Bitmap image = BitmapFactory.decodeFile(mFilePaths.get(position)); //Creation of Thumbnail of image
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(image);
}
else if(mFilePaths.get(position).contains(".mp4") || mFilePaths.get(position).contains(".3gp"))
{
Bitmap video = ThumbnailUtils.createVideoThumbnail(mFilePaths.get(position), imageWidth); //Creation of Thumbnail of video
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(video);
}
}
else
{
imageView = (ImageView)convertView;
}
return imageView;
}
/*
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mActivity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(mFilePaths.get(position), imageWidth, imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(image);
return imageView;
}
*/
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;
}
}
Inside your getView() function you're not setting the thumbnail correctly in the case where convertView is not null. Rearrange your code like this to handle that case:
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mActivity);
} else {
imageView = (ImageView) convertView;
}
if(mFilePaths.get(position).contains("jpg") || mFilePaths.get(position).contains("jpeg") ||
mFilePaths.get(position).contains("png"))
{
Bitmap image = BitmapFactory.decodeFile(mFilePaths.get(position)); //Creation of Thumbnail of image
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(image);
}
else if(mFilePaths.get(position).contains(".mp4") || mFilePaths.get(position).contains(".3gp"))
{
Bitmap video = ThumbnailUtils.createVideoThumbnail(mFilePaths.get(position), imageWidth); //Creation of Thumbnail of video
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(video);
}
return imageView;
}
The convertView parameter isn't a view that has already been initialized to the specified position, that you can return as is. It's a view that was being used to display a different grid element, that is being recycled for a different position, so you need to set it up.
Also, if you have laggy UI issues, look into creating your thumbnails in an AsyncTask or thread pool instead of on the main UI thread. Check out questions such as this one for information about how to do that: Loading images in a gridview with async task

Android: Resizing the gallery items

I'm using Gallery in my project. The features I want are listed below:
There should be 5 images visible at a time on the screen.
Number of images can increase or decrease dynamically.
The center image or we can say the selected image should be larger than rest of the four images.(0,1,[2],3,4).
The neighbouring images of center one should be smaller than the selected image but lagrer than the images at the corners.(0,[1],2,[3],4).
The images at the corners of the screen should be smaller than from rest of the images.
I don't know how to implenent this. I have channged the size of the center ImageView but I dont know how to set the size of rest of the four images. Please provide solution to this problem.
Here's my code for changing the size of ImageView
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class InfiniteGalleryResourceAdapter extends BaseAdapter {
/** The width of each child image */
private static final int G_ITEM_WIDTH = 60;
/** The height of each child image */
private static final int G_ITEM_HEIGHT = 250;
/** The context your gallery is running in (usually the activity) */
private Context mContext;
private int imageWidth;
private int imageHeight;
/** The array of resource ids to draw */
private final int[] imageIds;
public InfiniteGalleryResourceAdapter(Context c, int[] imageIds ) {
this.mContext = c;
this.imageIds = imageIds;
}
/**
* The count of how many items are in this Adapter
* This will return the max number as we want it to scroll as much as possible
*/
#Override
public int getCount() {
return imageIds.length;
}
#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) {
// convertView is always null in android.widget.Gallery
ImageView i = getImageView();
int itemPos = (position % imageIds.length);
try {
// first we calculate the item position in your list, because we have said the adapters size is Integer.MAX_VALUE
// the position getView gives us is not use-able in its current form, we have to use the modulus operator
// to work out what number in our 'array of paths' this actually equals
Log.d("item position", String.valueOf(itemPos));
i.setImageResource(imageIds[itemPos]);
((BitmapDrawable) i.getDrawable()).setAntiAlias(true); // Make sure we set anti-aliasing otherwise we get jaggies (non-smooth lines)
} catch (OutOfMemoryError e) {
// a 'just in case' scenario
Log.e("InfiniteGalleryResourceAdapter", "Out of memory creating imageview. Using empty view.", e);
}
return i;
}
/**
* Retrieve an ImageView to be used with the Gallery
* #return an ImageView with width and height set to DIP values
*/
private ImageView getImageView() {
setImageDimensions();
ImageView i = new ImageView(mContext);
i.setLayoutParams(new Gallery.LayoutParams(imageWidth, imageHeight));
i.setScaleType(ScaleType.CENTER_INSIDE);
return i;
}
/**
* Sets the dimensions for each View that is used in the gallery
* lazily initialized so that we don't have to keep converting over and over
*/
private void setImageDimensions() {
if (imageWidth == 0 || imageHeight == 0) {
imageWidth = AndroidUtils.convertToPix(mContext, G_ITEM_WIDTH);
imageHeight = AndroidUtils.convertToPix(mContext, G_ITEM_HEIGHT);
}
}
}

Categories

Resources