Friday, October 2, 2015

How to create an image gallery in android

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <GridView
        android:id="@+id/gv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:horizontalSpacing="5dp"
        android:verticalSpacing="5dp"
        android:padding="5dp"
        android:gravity="center"
        android:stretchMode="columnWidth"
        android:background="#fffefc"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.imagegallery;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Integer gridview_column_width=100; // Column width in DPs

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();

        GridView gv = (GridView) findViewById(R.id.gv);
        gv.setAdapter(new ImageAdapter(getApplicationContext()));
        setGridViewNumberOfColumns(gv);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(), i + "",Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(MainActivity.this,ImageDetails.class);
                intent.putExtra("position",i);
                startActivity(intent);
            }
        });
    }

    private void setGridViewNumberOfColumns(GridView gv){
        //Set the GridView number of columns
        int num_columns = Math.round(getScreenWidthInDPs()/gridview_column_width);
        if(num_columns <=2){
            gv.setNumColumns(GridView.AUTO_FIT);
        }
        else {
            gv.setNumColumns(num_columns);
        }
    }

    // Custom method to get the screen width in pixels
    private int getScreenWidthInDPs(){
        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        //Display dimensions in pixels
        display.getSize(size);
        int width = size.x;
        //int height = size.y;
        return getDPsFromPixels(width);
    }

    // Method for converting pixels value to dps
    private int getDPsFromPixels(int pixels){
        Resources r = mContext.getResources();
        int  dps = Math.round(pixels/(r.getDisplayMetrics().densityDpi/160f));
        return dps;
    }
}
ImageAdapter.java

package com.cfsuman.me.imagegallery;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.content.Context;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;

import java.io.IOException;
import java.io.InputStream;


public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private int image_width = 100; // In DPs
    private int image_height = 50; // In DPs
    private String image_folder = "animals";

    public ImageAdapter(Context c){
        mContext = c;
    }

    public int getCount(){
        return getImages().length;
    }

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

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


    // Create an ImageView for each item of Adapter
    public View getView(int position, View convertView, ViewGroup parent){
        ImageView iv;
        if(convertView == null){
            iv = new ImageView(mContext);
            iv.setLayoutParams(new LayoutParams(getPixelsFromDPs(image_width),
                    getPixelsFromDPs(image_height)));
            iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            iv.setPadding(5, 5, 5, 5);
            //iv.setBackgroundColor(Color.BLACK);
            iv.setBackground(mContext.getDrawable(R.drawable.image_bg));
        }else
        {
            iv = (ImageView) convertView;
        }

        String currentImage = image_folder +"/"+getImages()[position];
        Bitmap bitmap;
        try{
            InputStream is = mContext.getAssets().open(currentImage);
            bitmap = BitmapFactory.decodeStream(is);
            iv.setImageBitmap(bitmap);
        }catch (IOException e) {
            e.printStackTrace();
        }

        return iv;
    }

    private String[] getImages(){
        String images[] = new String[]{};
        try{
           images = mContext.getAssets().list(image_folder);
        }catch(IOException e)
        {
            Log.d("Asset: ", e.getMessage());
        }
        return images;
    }

    // Method for converting DP/DIP value to pixels
    private int getPixelsFromDPs(int dps){
        Resources r = mContext.getResources();
        int  px = (int) (TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dps, r.getDisplayMetrics()));
        return px;
    }
}
drawable/image_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke android:color="#32c9c9c9" android:width="1dp"/>
        </shape>
    </item>
</selector>
activity_image_details.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".ImageDetails"
    >
    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
ImageDetails.java

package com.cfsuman.me.imagegallery;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

public class ImageDetails extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_details);

        ViewPager vp = (ViewPager) findViewById(R.id.vp);
        ImagePagerAdapter adapter = new ImagePagerAdapter(getApplicationContext());
        vp.setAdapter(adapter);

        int position = getIntent().getIntExtra("position",-1);
        vp.setCurrentItem(position);
    }
}
ImagePagerAdapter.java

package com.cfsuman.me.imagegallery;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;


public class ImagePagerAdapter extends PagerAdapter {
    private Context mContext;
    private String image_folder = "animals";

    // Get image names from asset sub directory
    private String[] getImages(){
        String images[] = new String[]{};
        try{
            images = mContext.getAssets().list(image_folder);
        }catch(IOException e)
        {
            Log.d("Asset: ", e.getMessage());
        }
        return images;
    }

    ImagePagerAdapter(Context context){
        this.mContext=context;
    }

    @Override
    public int getCount() {
        return getImages().length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((ImageView) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView iv = new ImageView(mContext);
        iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

        final String currentImage = image_folder + "/"+getImages()[position];
        Bitmap bitmap;
        try{
            InputStream is = mContext.getAssets().open(currentImage);
            bitmap = BitmapFactory.decodeStream(is);
            iv.setImageBitmap(bitmap);
        }catch (IOException e) {
            e.printStackTrace();
        }
        container.addView(iv,0);

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mContext,currentImage,Toast.LENGTH_SHORT).show();
            }
        });
        return iv;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((ImageView)object);
    }
}




More android examples