Android Gallery Grid Example

1) Fragment of Grid

 
package com.kp.example.fragments;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import com.kaushal.example.R;
import com.kaushal.example.adapter.ImageAdapter;

/**
 * @author kaushal prajapati( kaushal2406@gmail.com)
 */
public class GridFragment extends Fragment {

    private ImageAdapter imageAdapter;
    ArrayList<String> files = new ArrayList<String>();// list of file paths
    File[] listFile;
    GridView imagegrid;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
    }
    public GridFragment() {

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_galary, container, false);
        imagegrid = (GridView) rootView.findViewById(R.id.PhoneImageGrid);

        imagegrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                String picuri = files.get(position);
                try {
                // your action on click goes here.
                    Log.d("test","test count picuri " + picuri ) ;
                    Uri uri = Uri.fromFile(new File(picuri));
                    Log.d("test","test count uri    " + uri.toString() ) ;
                    
                }catch (Exception e){
                    Log.d("Exception","Exception e " + e.getMessage());
                }

            }
        });

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int size = dm.widthPixels / 3;

        imageAdapter = new ImageAdapter(getActivity(),files,size);
        imagegrid.setAdapter(imageAdapter);

       // Toast.makeText(getActivity(), "oncreate ", Toast.LENGTH_SHORT).show();
        Log.d("test","test count oncreate " ) ;
        return rootView;
    }
    @Override
    public void onResume() {
        super.onResume();
        getFromSdcard();
    }
    public void getFromSdcard()
    {
 
        File file = new File(Environment.getExternalStoragePublicDirectory("").toString() + "/" + "Kaushal");
     
        if ((!file.exists()) && (!file.mkdirs())) {

            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                file.mkdir();
                file.mkdirs();
            }
            //return null;
        }
        Log.d("test","test count getPath " + file.getPath() + "   " +file.isDirectory() ) ;
        if (file.isDirectory())
        {
            listFile = file.listFiles();
            files = new ArrayList<String>();
            for (int i = 0; i < listFile.length; i++)
            {

                files.add(listFile[i].getAbsolutePath());
                Log.d("test","test count size " + listFile[i].getAbsolutePath() + " \nURI " +  listFile[i].toURI()) ;
               
            }
        }
        if(listFile.length==0){
            Toast.makeText(getActivity(), "Receipt List is Empty.", Toast.LENGTH_SHORT).show();
        }
        imageAdapter.setFiles(files);
        imageAdapter.notifyDataSetChanged();
    }
}

2) Layout of Fragment

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">
    <GridView
        android:id="@+id/PhoneImageGrid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:clipToPadding="true"
        android:columnWidth="250dp"
        android:fitsSystemWindows="true"
        android:gravity="center"
        android:horizontalSpacing="5dp"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:verticalSpacing="5dp" />
</LinearLayout> 

3) Image Adapter File

 
package com.kp.example.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import java.util.ArrayList;
import com.kp.example.R;

/**
 * Created by kaushal on 30/10/17.
 */

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    Context context;
    ArrayList<String> files = new ArrayList<String>();
    int size = 0;

    public ImageAdapter(Context context, ArrayList<String> files,int size) {
        this.context = context;
        this.files = files;
        this.size = size;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void setFiles(ArrayList<String> files) {
        this.files = files;
    }

    public int getCount() {
        return files.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }


    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;


        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.row_gelleryitem, null);
            holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
            convertView.setLayoutParams(new GridView.LayoutParams(size, size));
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Bitmap myBitmap = BitmapFactory.decodeFile(files.get(position));
        holder.imageview.setImageBitmap(myBitmap);
       // holder.imageview.setImageURI(Uri.parse(files.get(position)));     
        return convertView;
    }
    class ViewHolder {
        ImageView imageview;
    }
}

4) Item file for adapter

 
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/thumbImage"
        android:layout_width="match_parent"
        android:layout_height="175dp"
        android:layout_centerInParent="true"
        android:layout_margin="2dp"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop" />
</RelativeLayout>

5) Add permission in manifest file

 
 
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 

About

Software Developer in android,java,phone gap,angular js etc interested in challenging work in problem solving.

Leave a Reply