<p>In the previous article, we have talked about <strong><span style="color: #008000;"><a style="color: #008000;" href="https://c1ctech.com/android-sliding-views-using-viewpager-with-pageradapterfragmentpageradapter/">ViewPager</a></span></strong> to create swipe views in Android application in greater detail. In this article, we will talk about how to add buttons in different pages of viewPager, how to play and stop song on button click using MediaPlayer and also how to work with Mediaplayer on page scrolled.</p>
<p><strong><span style="color: #008000;">Get the full code from</span></strong> <span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://github.com/arunk7839/TestApp">here.</a></strong></span></p>
<p><span class="embed-youtube" style="text-align:center; display: block;"><amp-youtube data-videoid="eRXJYuM3UZs" data-param-rel="1" data-param-showsearch="0" data-param-showinfo="1" data-param-iv_load_policy="1" data-param-fs="1" data-param-hl="en-US" data-param-autohide="2" data-param-wmode="transparent" width="1200" height="675" layout="responsive"><a href="https://www.youtube.com/watch?v=eRXJYuM3UZs" placeholder><amp-img src="https://i.ytimg.com/vi/eRXJYuM3UZs/hqdefault.jpg" alt="YouTube Poster" layout="fill" object-fit="cover"><noscript><img src="https://i.ytimg.com/vi/eRXJYuM3UZs/hqdefault.jpg" loading="lazy" decoding="async" alt="YouTube Poster"></noscript></amp-img></a></amp-youtube></span></p>
<h3><strong><span style="color: #000080;">ViewPager</span></strong></h3>
<p>ViewPager is a layout widget which is capable of holding many child views and each child view represents a separate page. To insert child views that represent each page we need to hook up the viewpager to a <strong><span style="color: #008000;"><a style="color: #008000;" href="https://developer.android.com/reference/android/support/v4/view/PagerAdapter">pagerAdapter</a></span>.</strong></p>
<h3><span style="color: #000080;"><strong>Using PagerAdapter</strong></span></h3>
<p><span style="color: #008000;"><strong>PagerAdapter</strong></span> allow us to populate pages inside of a viewpager.</p>
<p>When you implement a PagerAdapter, you must override the following methods at minimum:</p>
<ul>
<li><strong><a href="http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#getCount()"><span style="color: #0000ff;">getCount()</span></a></strong> – Return the number of views available., i.e., number of pages to be displayed/created in the ViewPager.</li>
<li><strong><a href="http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#instantiateItem(android.view.ViewGroup,%20int)"><span style="color: #0000ff;">instantiateItem()</span></a> </strong>– This method will create the page for the given position passed to it as an argument. In our case, we inflate our layout resource which contains one imageView for image and one textView which will contain image related description. Finally, the inflated view is added to the container ( ViewPager) and return it as well.</li>
<li><strong><a href="http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#destroyItem(android.view.ViewGroup,%20int,%20java.lang.Object)"><span style="color: #0000ff;">destroyItem()</span></a> </strong>– Removes the page from the container for the given position. We simply removed object using <span style="color: #008000;"><a style="color: #008000;" href="http://developer.android.com/reference/android/view/ViewGroup.html#removeView(android.view.View)"><strong>removeView</strong>()</a></span> but could’ve also used <span style="color: #008000;"><strong><a style="color: #008000;" href="http://developer.android.com/reference/android/view/ViewGroup.html#removeViewAt(int)">removeViewAt()</a></strong></span> by passing it the position.</li>
<li><strong><span style="color: #0000ff;"><a style="color: #0000ff;" href="http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#isViewFromObject(android.view.View,%20java.lang.Object)">isViewFromObject()</a></span> </strong>– ViewPager associates each page with a key Object instead of working with Views directly. This key is used to track and uniquely identify a given page independent of its position in the adapter. This method checks whether the View passed to it (representing the page) is associated with that key object(returned by<strong> <span style="color: #008000;"><a style="color: #008000;" href="https://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#instantiateItem(android.view.ViewGroup,%20int)">instantiateItem(ViewGroup, int)</a></span></strong> or not. It is required by a PagerAdapter to function properly. It returns true if view is associated with the key object .</li>
</ul>
<h3><strong>C<span style="color: #000080;">reating New Project</span></strong></h3>
<p><strong>1</strong>.Create a new project in <span style="color: #008000;"><strong>Android Studio</strong></span> from <span style="color: #008000;"><strong>File ⇒ New Project</strong></span> by filling the required details. When it prompts you to select the activity, choose <span style="color: #008000;"><strong>Empty Activity</strong></span> and continue.</p>
<p><strong>2</strong>.Open the layout of the <strong>MainActivity</strong> i.e <strong><span style="color: #008000;">activity_main</span></strong> and add <strong><span style="color: #0000ff;">viewPager</span></strong> as shown below:</p>
<p><strong><span style="color: #008000;">activity_main.xml</span></strong></p>
<pre><;?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"
 tools:context=".MainActivity">;


 <;androidx.viewpager.widget.ViewPager
 android:id="@+id/viewpager"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 />;

<;/RelativeLayout>;</pre>
<p><strong>3</strong>.Inside <span style="color: #008000;"><strong>MainActivity</strong></span> before setting adapter in viewPager firstly we will create one layout file <span style="color: #008000;"><strong>content.xml</strong></span> which defines the view of a separate page adding to viewPager.</p>
<p><span style="color: #0000ff;"><strong>content.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent">;

 <;ImageView
 android:id="@+id/imageview"
 android:layout_width="190dp"
 android:layout_height="190dp"
 android:layout_alignParentTop="true"
 android:layout_centerInParent="true"
 android:layout_marginTop="12dp" />;

 <;TextView
 android:id="@+id/textview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/imageview"
 android:layout_centerInParent="true"
 android:layout_marginTop="12dp"
 android:textSize="36sp"
 android:textStyle="bold" />;

 <;LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/textview"
 android:layout_marginTop="12dp"
 android:orientation="horizontal">;

 <;Button
 android:id="@+id/btn_play"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_margin="8dp"
 android:background="@android:color/holo_green_light"
 android:layout_weight="5"
 android:textStyle="bold"
 android:textSize="18sp"
 android:text="Play" />;

 <;Button
 android:id="@+id/btn_stop"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textview"
 android:layout_centerHorizontal="true"
 android:layout_margin="8dp"
 android:background="@android:color/holo_red_light"
 android:layout_weight="5"
 android:textStyle="bold"
 android:textSize="18sp"
 android:text="Stop" />;

 <;/LinearLayout>;


 <;/RelativeLayout>;



</pre>
<p><strong>4</strong>.Under <span style="color: #0000ff;"><strong>res</strong></span> directory open <span style="color: #008000;"><strong>drawable</strong></span> folder and copy and paste all the images which you want to display like this as shown below:</p>
<p><img class="alignnone size-full wp-image-1236" src="https://c1ctech.com/wp-content/uploads/2019/09/Screenshot-2019-09-19-17.58.08-3061011925-1568961813624.png" alt="Screenshot 2019-09-19 17.58.08" width="514" height="237" /></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<p><strong>5</strong>.Create new folder <span style="color: #008000;"><strong>raw</strong></span> under <span style="color: #008000;"><strong>res</strong></span> directory and copy and paste all the songs which you want to play.</p>
<p><img class="alignnone size-full wp-image-1237" src="https://c1ctech.com/wp-content/uploads/2019/09/Screenshot-2019-09-19-18.04.57.png" alt="Screenshot 2019-09-19 18.04.57" width="510" height="198" /></p>
<p><strong>6</strong>.To set adapter in viewPager inside <span style="color: #008000;"><strong>MainActivity</strong></span> we will create a new class <span style="color: #0000ff;"><strong>MyPagerAdapter</strong></span> which extends <span style="color: #008000;"><strong>PagerAdapter</strong></span> and also don&#8217;t forget to override the methods which we have discussed above :</p>
<pre>private class MyPagerAdapter extends PagerAdapter {
 private int[] images;
 private String[] alphabets;
 int[] songs;


 private MyPagerAdapter() {
 this.images = new int[]{R.drawable.a_img, R.drawable.b_img, R.drawable.c_img, R.drawable.d_img};
 this.alphabets = new String[]{"A for Apple", "B for Ball", "C for cat", "D for Dog"};
 this.songs = new int[]{R.raw.wheels, R.raw.twinkle, R.raw.mary, R.raw.london};

 }

 public int getCount() {

 return this.images.length;
 }

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

 public Object instantiateItem(ViewGroup container, int position) {


 View view = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.content, container, false);

 <strong><span style="color: #0000ff;">//setting text in textview</span></strong>
 ((TextView) view.findViewById(R.id.textview)).setText(this.alphabets[position]);

 <strong><span style="color: #0000ff;">//setting image in imageview</span></strong>
 ImageView imageView = view.findViewById(R.id.imageview);
 imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
 imageView.setImageResource(this.images[position]);

 <strong><span style="color: #0000ff;">//play and stop song on button click</span></strong>
 Button btn_play = view.findViewById(R.id.btn_play);
 Button btn_stop = view.findViewById(R.id.btn_stop);


 final int song = songs[position];

 btn_play.setOnClickListener(new View.OnClickListener() {

 public void onClick(View v) {
 try {

 if (mp != null &;&; mp.isPlaying()) {
 mp.stop();
 mp.release();

 }
 mp = MediaPlayer.create(getApplicationContext(), song);
 mp.start();
 } catch (Exception e) {
 e.printStackTrace();
 }


 }
 });

 btn_stop.setOnClickListener(new View.OnClickListener() {

 public void onClick(View v) {
 mp.stop();
 mp.release();
 mp = MediaPlayer.create(getApplicationContext(), song);
 }
 });

 <strong><span style="color: #0000ff;">//adding view in container i.e viewpager</span></strong>
 container.addView(view);

 return view;

 }

 public void destroyItem(ViewGroup container, int position, Object object) {

 container.removeView((View) object);

 }
}</pre>
<p><strong>7</strong>.To viewPager add <span style="color: #0000ff;"><strong>addOnPageChangeListener</strong></span> that will be invoked whenever the page changes or we can say whenever you scrolled page.</p>
<pre>viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
 @Override
 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
 if (mp != null) {
 mp.stop();
 mp.release();
 mp = null;
 } else return;

 }

 @Override
 public void onPageSelected(int position) {

 }

 @Override
 public void onPageScrollStateChanged(int state) {

 }
});</pre>
<p><strong>8</strong>.Open <span style="color: #008000;"><strong>MainActivity.java</strong></span> and pass <span style="color: #0000ff;"><strong>MyPagerAdapter</strong></span> object as an argument while setting adapter to viewPager.</p>
<p><span style="color: #0000ff;"><strong>MainActivity.java</strong></span></p>
<pre>package trendlife.testapp;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

public class MainActivity extends AppCompatActivity {

 private ViewPager viewPager;

 MediaPlayer mp;

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


 viewPager = findViewById(R.id.viewpager);

 <strong><span style="color: #0000ff;">//setting adapter in viewpager</span></strong>
 viewPager.setAdapter(new MyPagerAdapter());

 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
 @Override
 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
 if (mp != null) {
 mp.stop();
 mp.release();
 mp = null;
 } else return;

 }

 @Override
 public void onPageSelected(int position) {

 }

 @Override
 public void onPageScrollStateChanged(int state) {

 }
 });

 }

 private class MyPagerAdapter extends PagerAdapter {
 private int[] images;
 private String[] alphabets;
 int[] songs;


 private MyPagerAdapter() {
 this.images = new int[]{R.drawable.a_img, R.drawable.b_img, R.drawable.c_img, R.drawable.d_img};
 this.alphabets = new String[]{"A for Apple", "B for Ball", "C for cat", "D for Dog"};
 this.songs = new int[]{R.raw.wheels, R.raw.twinkle, R.raw.mary, R.raw.london};

 }

 public int getCount() {

 return this.images.length;
 }

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

 public Object instantiateItem(ViewGroup container, int position) {


 View view = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.content, container, false);

 <strong><span style="color: #0000ff;">//setting text in textview</span></strong>
 ((TextView) view.findViewById(R.id.textview)).setText(this.alphabets[position]);

 <strong><span style="color: #0000ff;">//setting image in imageview</span></strong>
 ImageView imageView = view.findViewById(R.id.imageview);
 imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
 imageView.setImageResource(this.images[position]);

 <strong><span style="color: #0000ff;">//play and stop song on button click</span></strong>
 Button btn_play = view.findViewById(R.id.btn_play);
 Button btn_stop = view.findViewById(R.id.btn_stop);


 final int song = songs[position];

 btn_play.setOnClickListener(new View.OnClickListener() {

 public void onClick(View v) {
 try {

 if (mp != null &;&; mp.isPlaying()) {
 mp.stop();
 mp.release();

 }
 mp = MediaPlayer.create(getApplicationContext(), song);
 mp.start();
 } catch (Exception e) {
 e.printStackTrace();
 }


 }
 });

 btn_stop.setOnClickListener(new View.OnClickListener() {

 public void onClick(View v) {
 mp.stop();
 mp.release();
 mp = MediaPlayer.create(getApplicationContext(), song);
 }
 });

 <strong><span style="color: #0000ff;">//setting view in container i.e viewpager</span></strong>
 container.addView(view);

 return view;

 }

 public void destroyItem(ViewGroup container, int position, Object object) {

 container.removeView((View) object);

 }
 }

}</pre>
<p>When you run the application it will look like this:</p>
<p><img class="alignnone wp-image-1238" src="https://c1ctech.com/wp-content/uploads/2019/09/Screenshot_1568902634-576x1024.png" alt="Screenshot_1568902634" width="244" height="434" /> <img class="alignnone wp-image-1239" src="https://c1ctech.com/wp-content/uploads/2019/09/Screenshot_1568902644.png" alt="Screenshot_1568902644" width="243" height="432" /></p>
<p> ;</p>


