Saturday, 8 March 2014

Gallery using ViewPager Example in Android

ScreenShots:



 

you can download the images those are used in this project from this link https://www.google.co.in/search?q=android+images&tbm=isch&tbo=u&source=univ&sa=X&ei=oPAaU-K9Cc-eiQfE1IDIDQ&ved=0CCcQsAQ&biw=1366&bih=677


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.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


MainActivity.java:
package com.ram.galleryusingviewpager;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private int[] IMAGES = { R.drawable.android1, R.drawable.android2,
            R.drawable.android3, R.drawable.android4, R.drawable.android5,
            R.drawable.android6 };

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

        ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImageAdapter adapter = new ImageAdapter();
        viewPager.setAdapter(adapter);
    }

    class ImageAdapter extends PagerAdapter {

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

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setImageResource(IMAGES[position]);
            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

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

2 comments: