Android ViewPager with Mediaplayer

In the previous article, we have talked about ViewPager 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.

Get the full code from here.

ViewPager

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 pagerAdapter.

Using PagerAdapter

PagerAdapter allow us to populate pages inside of a viewpager.

When you implement a PagerAdapter, you must override the following methods at minimum:

  • getCount() – Return the number of views available., i.e., number of pages to be displayed/created in the ViewPager.
  • instantiateItem() – 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.
  • destroyItem() – Removes the page from the container for the given position. We simply removed object using removeView() but could’ve also used removeViewAt() by passing it the position.
  • isViewFromObject() – 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 instantiateItem(ViewGroup, int) or not. It is required by a PagerAdapter to function properly. It returns true if view is associated with the key object .

Creating New Project

1.Create a new project in Android Studio from File ⇒ New Project by filling the required details. When it prompts you to select the activity, choose Empty Activity and continue.

2.Open the layout of the MainActivity i.e activity_main and add viewPager as shown below:

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"
    tools:context=".MainActivity">


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

</RelativeLayout>

3.Inside MainActivity before setting adapter in viewPager firstly we will create one layout file content.xml which defines the view of a separate page adding to viewPager.

content.xml

<?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>



4.Under res directory open drawable folder and copy and paste all the images which you want to display like this as shown below:

Screenshot 2019-09-19 17.58.08

5.Create new folder raw under res directory and copy and paste all the songs which you want to play.

Screenshot 2019-09-19 18.04.57

6.To set adapter in viewPager inside MainActivity we will create a new class MyPagerAdapter which extends PagerAdapter and also don’t forget to override the methods which we have discussed above :

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);

        //setting text in textview
        ((TextView) view.findViewById(R.id.textview)).setText(this.alphabets[position]);

        //setting image in imageview
        ImageView imageView = view.findViewById(R.id.imageview);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setImageResource(this.images[position]);

        //play and stop song on button click
        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);
            }
        });

        //adding view in container i.e viewpager
        container.addView(view);

        return view;

    }

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

        container.removeView((View) object);

    }
}

7.To viewPager add  addOnPageChangeListener  that will be invoked whenever the page changes or we can say whenever you scrolled page.

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) {

    }
});

8.Open MainActivity.java and pass MyPagerAdapter object as an argument while setting adapter to viewPager.

MainActivity.java

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);

        //setting adapter in viewpager
        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);

            //setting text in textview
            ((TextView) view.findViewById(R.id.textview)).setText(this.alphabets[position]);

            //setting image in imageview
            ImageView imageView = view.findViewById(R.id.imageview);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageResource(this.images[position]);

            //play and stop song on button click
            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);
                }
            });

            //setting view in container i.e viewpager
            container.addView(view);

            return view;

        }

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

            container.removeView((View) object);

        }
    }

}

When you run the application it will look like this:

Screenshot_1568902634              Screenshot_1568902644

 

Leave a Reply