How to create GridView image gallery programmatically in android? - android

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

Related

how to show all photos using AsyncTask

I want to collect all photos in pictures directory to show them in GridView, so tried with two ways.
1_ without using AsyncTask: this way worked very well but it has a problem which is that the app freezes for seconds to get all photos in specified directory and it's sub directories.
2_using AsyncTask: this way doesn't get any images and the list of images is always empty, I know that I should use Asynctask for processes that take mush time to processed and I don't know what I missed when using AsyncTask.
what I want is to find a way to collect all photos using AsyncTask with app freezing and thanks in advance.
public static class ImagesFragment extends Fragment {
static List<Image> imagesList = new ArrayList<>();
GridViewRecyclerAdapter gridViewRecyclerAdapter;
GridView gridView;
Spinner spinner;
public static File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// imagesList = loadImageData(file);
gridViewRecyclerAdapter = new GridViewRecyclerAdapter(imagesList, getContext());
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_images, container, false);
spinner = view.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
break;
case 1:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
gridView = view.findViewById(R.id.grid_view);
gridView.setAdapter(gridViewRecyclerAdapter);
return view;
}
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 List<Image> loadImageData(File file) {
String fileType;
String extension;
if(file.isDirectory()){
File[] files = file.listFiles();
for(File file1: files){
if(file1.isDirectory())
loadImageData(file1);
else{
extension = MimeTypeMap.getFileExtensionFromUrl(file1.getPath());
if (extension != null) {
fileType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if(fileType != null)
if(fileType.contains("image")){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file1.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight())
imagesList.add(new Image(bitmap, file1.getName(), file1.getPath()));
}
}
}
}
}
else {
extension = MimeTypeMap.getFileExtensionFromUrl(file.getPath());
if (extension != null) {
fileType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if(fileType != null)
if(fileType.contains("image")){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imagesList.add(new Image(bitmap, file.getName(), file.getPath()));
}
}
}
return imagesList;
}
}
public static class GridViewRecyclerAdapter extends BaseAdapter {
List<Image> imageList;
Context context;
static int position;
public GridViewRecyclerAdapter(List<Image> imageList, Context context){
this.imageList = imageList;
this.context = context;
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Object getItem(int position) {
return imageList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.images_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = convertView.findViewById(R.id.image_view);
viewHolder.imageView.setTag(imageList.get(position).path);
viewHolder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) convertView.getTag();
new LoadImageAsyncTask().execute(ImagesFragment.file.getAbsolutePath());
viewHolder.imageView.setImageBitmap(imageList.get(position).bitmap);
viewHolder.textView.setText(imageList.get(position).title);
GridViewRecyclerAdapter.position = position;
return convertView;
}
public static class ViewHolder{
ImageView imageView;
TextView textView;
}
static class LoadImageAsyncTask extends AsyncTask<String, Void, List<Image>> {
#Override
protected List<Image> doInBackground(String... objects) {
ImagesFragment.imagesList = ImagesFragment.loadImageData(new File(objects[0]));
return ImagesFragment.imagesList;
}
}
}

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..

GridView with equal rows

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

List View changes position of ImageView On scroll

I am using List View with custom array adapter the adapter sets data from Sqlite. But when the list items reach over 10 (or list becomes scroll able) the Image View changes position automatically if i scrolls continue. here is my custom adapter's code.Thanks
public class CustomeAdapter extends ArrayAdapter<String>{
public Context context;
public ArrayList<String> titleArrayList, descArrayList, timeArrayList, imgArrayList, IdArrayList;
List data;
int layoutResID;
private Bitmap myBitmap;
public CustomeAdapter(Context context, int layoutResourceId, ArrayList<String> titleArrayList, ArrayList<String> descArrayList, ArrayList<String> timeArrayList, ArrayList<String> imgArrayList, ArrayList<String> IdArrayList) {
super(context, layoutResourceId, titleArrayList);
this.context = context;
this.titleArrayList = titleArrayList;
this.descArrayList = descArrayList;
this.timeArrayList = timeArrayList;
this.imgArrayList = imgArrayList;
this.IdArrayList = IdArrayList;
this.data = data;
this.layoutResID = layoutResourceId;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
final StockQuoteView sqView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(layoutResID, parent, false);
sqView = new StockQuoteView();
sqView.tag = (TextView) rowView.findViewById(R.id.tv_fullnote);
sqView.desc = (TextView) rowView.findViewById(R.id.tv_title);
sqView.time = (TextView) rowView.findViewById(R.id.tv_time);
sqView.id = (TextView) rowView.findViewById(R.id.id);
sqView.img = (ImageView) rowView.findViewById(R.id.imageView3);
sqView.button1 = (ImageView) rowView.findViewById(R.id.swipe_button1);
sqView.button2 = (ImageView) rowView.findViewById(R.id.swipe_button2);
sqView.button3 = (ImageView) rowView.findViewById(R.id.swipe_button3);
sqView.button4 = (ImageView) rowView.findViewById(R.id.swipe_button4);
rowView.setTag(sqView);
} else {
sqView = (StockQuoteView) rowView.getTag();
}
try {
sqView.tag.setText(titleArrayList.get(position));
sqView.desc.setText(descArrayList.get(position));
sqView.time.setText(timeArrayList.get(position));
sqView.id.setText(IdArrayList.get(position));
sqView.id.setTag(IdArrayList.get(position).toString());
if (imgArrayList.get(position).contains("null")) {
sqView.img.setImageBitmap(null);
sqView.img.setTag("null");
} else {
myBitmap = BitmapFactory.decodeFile(imgArrayList.get(position));
//sqView.img.setImageBitmap((position & 1) == 1 ? myBitmap : myBitmap);
String TAG = "tag";
String id = String.valueOf(position);
sqView.img.setTag(imgArrayList.get(position).toString());
int width = myBitmap.getWidth();
int height = myBitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width) ? height - (height - width) : height;
int crop = (width - height) / 2;
crop = (crop < 0) ? 0 : crop;
Bitmap cropImg = Bitmap.createBitmap(myBitmap, crop, 0, newWidth, newHeight);
sqView.img.setImageBitmap(cropImg);
}
} catch (Exception e) {
System.out.print(e.toString());
}
return rowView;
}
protected static class StockQuoteView {
protected TextView tag;
protected TextView desc;
protected TextView time;
protected ImageView img;
protected ImageView button1;
protected ImageView button2;
protected ImageView button3;
protected ImageView button4;
public TextView id;
}
}
`
put this linesqView.img.setVisibility(View.INVISIBLE) after sqView.img.setTag("null"); and Make Visible back the imageView in the else statment like else {sqView.img.setVisibility(View.VISIBLE)
myBitmap = BitmapFactory.decodeFile(imgArrayList.get(position));
//sqView.img.setImageBitmap((position & 1) == 1 ? myBitmap : myBitmap);
String TAG = "tag";
String id = String.valueOf(position);............}
this is tricked only.

Sort Image according to DATE and TIME inside gridview android

//The Path where my images are saving
/storage/emulated/0/Pictures/CameraExample/JPEG_20150107_152640.jpeg
//This is one of the file path.
//I need to sort images like last taken photo as the first one to display //inside the grid view as of now images are displayed, recent photo at the //last.
Below is my code
public class ImageAdapter extends BaseAdapter{
private Context context;
private int imageWidth;
private Activity activity;
ArrayList<String> itemList = new ArrayList<String>();
Bitmap bitmap;
public ImageAdapter(Activity activity,ArrayList<String> itemList,int imageWidth) {
this.activity = activity;
this.itemList = itemList;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.itemList.size();
}
void add(String path) {
itemList.add(path);
}
#Override
public Object getItem(int position) {
return this.itemList.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;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth ,imageWidth ));
bitmap = decodeFile(itemList.get(position), imageWidth, imageWidth);
imageView.setImageBitmap(bitmap);
imageView.setOnClickListener( new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements View.OnClickListener {
int position;
public OnImageClickListener(int position){
this.position = position;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ImageDisplayActivity.class);
intent.putExtra("position", position);
Log.d("ImageAdapter","Intent.putExtra ");
activity.startActivity(intent);
}
}
public Bitmap decodeFile(String path, int reqWidth, int reqHeight) {
try {
File f = new File(path);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = reqWidth;
final int REQUIRED_HEIGHT = reqHeight;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH && o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
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;
}
}
// And Finally when I scroll my grid view . Scrolling is not so smooth. Please help me in solving two problems.
// My GridView Activity Class
public class GridViewActivity extends Activity {
private ImageAdapter imageAdapter;
private HelperUtils utils;
private ArrayList<String> itemList = new ArrayList<String>();
private GridView gridView;
private int columnWidth;
private Activity activity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
gridView = (GridView) findViewById(R.id.gridView);
utils = new HelperUtils(this);
InitilizeGridLayout();
itemList = utils.getFilePaths();
imageAdapter = new ImageAdapter(this, itemList, columnWidth);
gridView.setAdapter(imageAdapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, HelperAppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((HelperAppConstant.NUM_OF_COLUMNS + 1) * padding)) / HelperAppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(HelperAppConstant.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);
}
}
Remove the Collections.sort(itemList); from your getView method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
Log.d("ImageAdapter","Inside the if condition");
imageView = new ImageView(activity);
}
else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth ,imageWidth ));
// bitmap = decodeFile(itemList.get(position), imageWidth, imageWidth);
bitmap = decodeFile(getItem(position), imageWidth, imageWidth);
imageView.setImageBitmap(bitmap);
return imageView;
}
Sort the list just before you populate your grid view in your onCreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
gridView = (GridView) findViewById(R.id.gridView);
utils = new HelperUtils(this);
InitilizeGridLayout();
itemList = utils.getFilePaths();
Collections.sort(itemList);
imageAdapter = new ImageAdapter(this, itemList, columnWidth);
gridView.setAdapter(imageAdapter);
}
You could follow the example in this link by creating a list of items that contains the image file path and the image bitmap. This way, you wouldn't have to decode the bitmap everytime getView is called. You could just decode it once before you populate the gridview.
Since the images are sorted in ascending order, you can replace you getItem method with the one below:
#Override
public Object getItem(int position) {
return this.itemList.get(itemList.size() - 1 - position);
}
I updated the getView method. You should use getItem(position) instead of itemList.get(position) to decode the bitmap.
For making your scroll smooth you have to display the images with Picasso library, I had the same issue !

Categories

Resources