Wednesday, March 25, 2015

Implement OnPageChangeListener for ViewPager to monitor the current visible page

Refer to the former example of "Example of ViewPager with custom PagerAdapter": at start-up, instantiateItem() of MyPagerAdapter will be called twice, with position 0 and 1. When you you scroll page forward, extra instantiateItem() with position of the next invisible page will be called. And when you you scroll page backward, extra instantiateItem() with position of the former invisible page will be called.

So how can you know when page is scrolled, and which page is currently visible? One approach is to implement OnPageChangeListener for the ViewPager. The onPageSelected(int position) method will be called when a new page becomes selected. But not the first page at start-up.

Example:


package com.example.androidviewpagerapp;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

 ViewPager viewPager;
 MyPagerAdapter myPagerAdapter;
 TextView textMsg;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textMsg = (TextView)findViewById(R.id.msg);
  textMsg.setMovementMethod(new ScrollingMovementMethod());
  
  viewPager = (ViewPager) findViewById(R.id.myviewpager);
  myPagerAdapter = new MyPagerAdapter();
  viewPager.setAdapter(myPagerAdapter);
  
  viewPager.setOnPageChangeListener(myOnPageChangeListener);
 }
 
 OnPageChangeListener myOnPageChangeListener = 
   new OnPageChangeListener(){

  @Override
  public void onPageScrollStateChanged(int state) {
   //Called when the scroll state changes.
  }

  @Override
  public void onPageScrolled(int position, 
    float positionOffset, int positionOffsetPixels) {
   //This method will be invoked when the current page is scrolled, 
   //either as part of a programmatically initiated smooth scroll 
   //or a user initiated touch scroll.
  }

  @Override
  public void onPageSelected(int position) {
   //This method will be invoked when a new page becomes selected.
   textMsg.append("onPageSelected:" + position + "\n");
  }};

 private class MyPagerAdapter extends PagerAdapter {

  int NumberOfPages = 5;

  int[] res = { android.R.drawable.ic_dialog_alert,
    android.R.drawable.ic_menu_camera,
    android.R.drawable.ic_menu_compass,
    android.R.drawable.ic_menu_directions,
    android.R.drawable.ic_menu_gallery };
  int[] backgroundcolor = { 0xFF101010, 0xFF202020, 0xFF303030,
    0xFF404040, 0xFF505050 };

  @Override
  public int getCount() {
   return NumberOfPages;
  }

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

  @Override
  public Object instantiateItem(ViewGroup container, int position) {
   
   textMsg.append("instantiateItem:" + position + "\n");

   TextView textView = new TextView(MainActivity.this);
   textView.setTextColor(Color.WHITE);
   textView.setTextSize(30);
   textView.setTypeface(Typeface.DEFAULT_BOLD);
   textView.setText(String.valueOf(position));

   ImageView imageView = new ImageView(MainActivity.this);
   imageView.setImageResource(res[position]);
   LayoutParams imageParams = new LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   imageView.setLayoutParams(imageParams);

   LinearLayout layout = new LinearLayout(MainActivity.this);
   layout.setOrientation(LinearLayout.VERTICAL);
   LayoutParams layoutParams = new LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   layout.setBackgroundColor(backgroundcolor[position]);
   layout.setLayoutParams(layoutParams);
   layout.addView(textView);
   layout.addView(imageView);

   final int page = position;
   layout.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
     Toast.makeText(MainActivity.this,
       "Page " + page + " clicked", Toast.LENGTH_LONG)
       .show();
    }
   });

   container.addView(layout);
   return layout;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
   container.removeView((LinearLayout) object);
   
   textMsg.append("destroyItem:" + position + "\n");
  }

 }
}

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidviewpagerapp.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp" >

        <TextView
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="bottom" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/myviewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>



download filesDownload the files.

Next:
- ViewPager auto scroll to the first, last or any page

1 comment:

  1. OnPageChangeListener is deprecated it is replaced with addOnPageChangeListener Thanks For your answer

    ReplyDelete