Skip to main content

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

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout 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:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…