Skip to main content

How to use ViewPager 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"
    android:background="#7b9684"
    >
    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.viewpagerexample;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Window;


public class MainActivity extends AppCompatActivity {
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request action bar window feature
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the support action bar and set a background color for it
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#D96B9663")));

        // Get the application context
        mContext = getApplicationContext();

        /*
            ViewPager
                Layout manager that allows the user to flip left and right through pages of data.
                You supply an implementation of a PagerAdapter to generate the pages that the view shows.
        */
        // Get the widget reference from XML layout
        ViewPager vp = (ViewPager) findViewById(R.id.vp);

        // Initialize a new PagerAdapter instance
        ImagePagerAdapter adapter = new ImagePagerAdapter(mContext);

        // Set the PagerAdapter for ViewPager object
        vp.setAdapter(adapter);
    }
}
ImagePagerAdapter.java

package com.cfsuman.me.viewpagerexample;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.content.Context;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.graphics.Bitmap;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Typeface;
import android.view.ViewGroup.MarginLayoutParams;

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


// Base class providing the adapter to populate pages inside of a ViewPager.
public class ImagePagerAdapter extends PagerAdapter {
    private Context mContext;
    private String imageFolder="animals";

    /*
        When you implement a PagerAdapter, you must override the following methods at minimum:
            instantiateItem(ViewGroup, int)
            destroyItem(ViewGroup, int, Object)
            getCount()
            isViewFromObject(View, Object)
     */

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

    // Get images from assets sub folder.
    private String[] getImages(){
        String[] images = new String[]{};
        try{
            images = mContext.getAssets().list(imageFolder);
        }catch(IOException e){
            e.printStackTrace();
        }
        return images;
    }

    /*
        public abstract int getCount ()
            Return the number of views available.
    */
    @Override
    public int getCount(){
        return getImages().length;
    }

    /*
        public abstract boolean isViewFromObject (View view, Object object)
            Determines whether a page View is associated with a specific key object as returned by
            instantiateItem(ViewGroup, int). This method is required for a
            PagerAdapter to function properly.

            Parameters
                view : Page View to check for association with object
                object : Object to check for association with view

            Returns
                true : if view is associated with the key object object
    */
    @Override
    public boolean isViewFromObject(View view, Object object){
        return view == (RelativeLayout)object;
    }

    /*
        public Object instantiateItem (ViewGroup container, int position)
            Create the page for the given position. The adapter is responsible for adding the view
            to the container given here, although it only must ensure this is done by the time it
            returns from finishUpdate(ViewGroup).

            Parameters
                container : The containing View in which the page will be shown.
                position : The page position to be instantiated.

            Returns
                Returns an Object representing the new page. This does not need to be a View, but
                can be some other container of the page.
    */
    @Override
    public Object instantiateItem(ViewGroup container, int position){
        // Create a new LayoutParams object
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        // Initialize a new RelativeLayout instance
        RelativeLayout rl = new RelativeLayout(mContext);
        rl.setLayoutParams(params);
        rl.setBackgroundColor(Color.parseColor("#FF63796A"));
        rl.setPadding(5,5,10,10);

        // Initialize a new ImageView instance
        ImageView iv = new ImageView(mContext);
        iv.setLayoutParams(new LayoutParams(params));
        // Set the ImageView background color
        iv.setBackgroundColor(Color.parseColor("#FF9DB6A5"));
        // Set ImageView padding
        iv.setPadding(15, 15, 15, 15);

        // Generate the current image file path
        final String currentImageFile = imageFolder+"/"+ getImages()[position];

        // Try to set the ImageView image from asset image
        try{
            Bitmap bitmap;
            InputStream is = mContext.getAssets().open(currentImageFile);
            bitmap = BitmapFactory.decodeStream(is);
            iv.setImageBitmap(bitmap);
        }catch(IOException e){
            e.printStackTrace();
        }
        // Specify ImageView image scaling type
        iv.setScaleType(ScaleType.FIT_CENTER);

        // Set a click listener for ImageView
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mContext, currentImageFile, Toast.LENGTH_SHORT).show();
            }
        });

        TextView tv = new TextView(mContext);
        // Set the layout parameters for TextView
        tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        // Put the TextView at the bottom right of RelativeLayout
        ((LayoutParams)tv.getLayoutParams()).addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        ((LayoutParams)tv.getLayoutParams()).addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        // Set the TextView font size
        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
        // Set the TextView font and text style
        tv.setTypeface(Typeface.MONOSPACE, Typeface.ITALIC);

        // Set the TextView padding
        tv.setPadding(10, 10, 10, 10);
        // Set TextView background color to transparent white
        tv.setBackgroundColor(Color.parseColor("#25FFFFFF"));
        // Set the TextView text
        tv.setText("Image " + (position + 1) + " of " + getCount());
        tv.setTextColor(Color.BLACK);

        // Set the TextView margins
        MarginLayoutParams mlp = (MarginLayoutParams)tv.getLayoutParams();
        mlp.setMargins(10,10,10,10);

        // Add the TextView to RelativeLayout
        rl.addView(tv,0);
        // Add the ImageView to RelativeLayout
        rl.addView(iv,0);

        // Add the RelativeLayout to the container
        container.addView(rl);

        // Finally, return the RelativeLayout as page of ViewPager
        return rl;
    }

    /*
        public void destroyItem (ViewGroup container, int position, Object object)
            Remove a page for the given position. The adapter is responsible for removing the view
            from its container, although it only must ensure this is done by the time
            it returns from finishUpdate(ViewGroup).

            Parameters
                container : The containing View from which the page will be removed.
                position : The page position to be removed.
                object : The same object that was returned by instantiateItem(View, int).
    */
    public void destroyItem(ViewGroup container, int position, Object object){
        // Remove the page from ViewPager object
        container.removeView((RelativeLayout) 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=&…