Tutorials Android How to Customize YouTubePlayer Controls in Android

How to Customize YouTubePlayer Controls in Android

The YouTube Android Player allows you to customize the playback control by setting one of the style defined in YouTubePlayer.PlayerStyle enumeration. It currently support three styles DEFAULT, MINIMAL or CHROMELESS;

  • YouTubePlayer.PlayerStyle.DEFAULT – The default style, showing all interactive player controls.
  • YouTubePlayer.PlayerStyle.MINIMAL – The minimal style displays only a time bar and play/pause controls.
  • YouTubePlayer.PlayerStyle.CHROMELESS – A style that shows no interactive player controls. When you use CHROMELESS, you need to write your own controls for play, pause or seek operation.

You can apply style to YouTubePlayer by calling setPlayerStyle(PlayerStyle style) method.

player.setPlayerStyle(PlayerStyle.CHROMELESS);

In our previous example, we saw How to use YouTube Android Player API and YouTubePlayerView. In this example, we will customize the YouTubePlayer with custom player controls.

Customize YouTubePlayer Controls in Android

1. Add YouTubePlayerView to View Hierarchy

Let us first add the YouTubePlayerView view in your activity or fragment view hierarchy.

activity_custom_player.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.stacktips.youtube.MainActivity">

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ebeff2" />

</LinearLayout>

Let us now add the player controls right below YouTubePlayerView in activity_custom_player.xml layout.

<LinearLayout
    android:id="@+id/video_control"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#444"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:visibility="gone"
    android:weightSum="10">

    <ImageButton
        android:id="@+id/play_video"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:background="@null"
        android:src="@drawable/ic_play" />

    <ImageButton
        android:id="@+id/pause_video"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:background="@null"
        android:src="@drawable/ic_pause" />

    <SeekBar
        android:id="@+id/video_seekbar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_weight="6"
        android:max="100"
        android:progress="0" />

    <TextView
        android:id="@+id/play_time"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="2"
        android:text="--:--"
        android:textColor="@android:color/white" />
</LinearLayout>

2. Add INTERNET Permission in AndroidManifest

INTERNET permission is required to play video over internet. Add the following permission in your application AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />

3. Initialize YouTubePlayerView

When using YouTubePlayerView, your activity needs to extend YouTubeBaseActivity. Now let us create an Activity that extends YouTubeBaseActivity and initialize the YouTubePlayerView. We will add our own Play, Pause and Seek playback control.

public class CustomPlayerControlActivity extends YouTubeBaseActivity 
        implements OnInitializedListener, View.OnClickListener {
    private static final String TAG = "CustomPlayerControlActivity";

    public static final String API_KEY = "AIzaSyBx7v0YOb140fDO732fMx4l87raxezDWFw";

    //https://www.youtube.com/watch?v=<VIDEO_ID>
    public static final String VIDEO_ID = "-m3V8w_7vhk";

    private YouTubePlayer mPlayer;

    private View mPlayButtonLayout;
    private TextView mPlayTimeTextView;

    private Handler mHandler = null;
    private SeekBar mSeekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // attaching layout xml
        setContentView(R.layout.activity_custom_player);

        // Initializing YouTube player view
        YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player_view);
        youTubePlayerView.initialize(API_KEY, this);

        //Add play button to explicitly play video in YouTubePlayerView
        mPlayButtonLayout = findViewById(R.id.video_control);
        findViewById(R.id.play_video).setOnClickListener(this);
        findViewById(R.id.pause_video).setOnClickListener(this);

        mPlayTimeTextView = (TextView) findViewById(R.id.play_time);
        mSeekBar = (SeekBar) findViewById(R.id.video_seekbar);
        mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener);

        mHandler = new Handler();
    }

    @Override
    public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
        Toast.makeText(this, "Failed to initialize.", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
        if (null == player) return;
        mPlayer = player;

        displayCurrentTime();

        // Start buffering
        if (!wasRestored) {
            player.cueVideo(VIDEO_ID);
        }

        player.setPlayerStyle(PlayerStyle.CHROMELESS);
        mPlayButtonLayout.setVisibility(View.VISIBLE);

        // Add listeners to YouTubePlayer instance
        player.setPlayerStateChangeListener(mPlayerStateChangeListener);
        player.setPlaybackEventListener(mPlaybackEventListener);
    }

    PlaybackEventListener mPlaybackEventListener = new PlaybackEventListener() {
        @Override
        public void onBuffering(boolean arg0) {
        }

        @Override
        public void onPaused() {
            mHandler.removeCallbacks(runnable);
        }

        @Override
        public void onPlaying() {
            mHandler.postDelayed(runnable, 100);
            displayCurrentTime();
        }

        @Override
        public void onSeekTo(int arg0) {
            mHandler.postDelayed(runnable, 100);
        }

        @Override
        public void onStopped() {
            mHandler.removeCallbacks(runnable);
        }
    };

    PlayerStateChangeListener mPlayerStateChangeListener = new PlayerStateChangeListener() {
        @Override
        public void onAdStarted() {
        }

        @Override
        public void onError(ErrorReason arg0) {
        }

        @Override
        public void onLoaded(String arg0) {
        }

        @Override
        public void onLoading() {
        }

        @Override
        public void onVideoEnded() {
        }

        @Override
        public void onVideoStarted() {
            displayCurrentTime();
        }
    };

    SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            long lengthPlayed = (mPlayer.getDurationMillis() * progress) / 100;
            mPlayer.seekToMillis((int) lengthPlayed);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_video:
                if (null != mPlayer && !mPlayer.isPlaying())
                    mPlayer.play();
                break;
            case R.id.pause_video:
                if (null != mPlayer && mPlayer.isPlaying())
                    mPlayer.pause();
                break;
        }
    }

    private void displayCurrentTime() {
        if (null == mPlayer) return;
        String formattedTime = formatTime(mPlayer.getDurationMillis() - mPlayer.getCurrentTimeMillis());
        mPlayTimeTextView.setText(formattedTime);
    }

    private String formatTime(int millis) {
        int seconds = millis / 1000;
        int minutes = seconds / 60;
        int hours = minutes / 60;

        return (hours == 0 ? "--:" : hours + ":") + String.format("%02d:%02d", minutes % 60, seconds % 60);
    }


    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            displayCurrentTime();
            mHandler.postDelayed(this, 100);
        }
    };
}

4. Download Complete Source Code

[download url=”https://github.com/StacktipsLab/YouTubePlayerView-Example” meta=”Download YouTube Android Player API example source code from our GitHub repository. The source code contains examples of different YouTubePlayer styles and customised controls.”]
Total
6
Shares
guest
19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Nilanchala Panigrahy
Nilanchala Panigrahy
6 years ago

You can update the seeker progress by calling setProgress() inside by inside onProgressChanged() method.

nikeru8
nikeru8
5 years ago

i want to know how to do either.
I put seekBar.setProgress(progress); inside onProgressChanged() but do not work.

nikeru8
nikeru8
5 years ago

I need help to solve this.
I did what u said. but is not work for me.
mSeekBar.setProgress(progress); in onProgressChanged() doesn’t work.

hasan khan
hasan khan
3 years ago
Reply to  nikeru8

did u solve it???

Ayaz khan
Ayaz khan
3 years ago
Reply to  hasan khan

no help me

pronojit
pronojit
6 years ago

video just playing for 2 sec. what the problem

Nilanchala Panigrahy
Nilanchala Panigrahy
6 years ago
Reply to  pronojit

Is your network stable? Please check your device connection settings or test with a different video id.

pronojit
pronojit
6 years ago

yes my network stable.i have change the video id but the problem is same .here is my code sample

public class MainActivity extends YouTubeBaseActivity implements OnInitializedListener, View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
public static final String API_KEY = “AIzaSyAY0R90NijWclVSTvwJ5avUDvXZz1zO4EA”;

//https://www.youtube.com/watch?v=
public static final String VIDEO_ID = “Z_PODraXg4E”;

private YouTubePlayer mPlayer;

private View mPlayButtonLayout;
private TextView mPlayTimeTextView;

private Handler mHandler = null;
private SeekBar mSeekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initializing YouTube player view
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player_view);
youTubePlayerView.initialize(API_KEY, this);

//Add play button to explicitly play video in YouTubePlayerView
mPlayButtonLayout = findViewById(R.id.video_control);
findViewById(R.id.play_video).setOnClickListener(this);
findViewById(R.id.pause_video).setOnClickListener(this);

mPlayTimeTextView = (TextView) findViewById(R.id.play_time);
mSeekBar = (SeekBar) findViewById(R.id.video_seekbar);
mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener);

mHandler = new Handler();
}

@Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, “Failed to initialize.”, Toast.LENGTH_LONG).show();
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (null == player) return;
mPlayer = player;

displayCurrentTime();

// Start buffering
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}

player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
mPlayButtonLayout.setVisibility(View.VISIBLE);

// Add listeners to YouTubePlayer instance
player.setPlayerStateChangeListener(mPlayerStateChangeListener);
player.setPlaybackEventListener(mPlaybackEventListener);

}

PlaybackEventListener mPlaybackEventListener = new PlaybackEventListener() {
@Override
public void onBuffering(boolean arg0) {
}

@Override
public void onPaused() {
mHandler.removeCallbacks(runnable);
}

@Override
public void onPlaying() {
mHandler.postDelayed(runnable, 100);
displayCurrentTime();
}

@Override
public void onSeekTo(int arg0) {
mHandler.postDelayed(runnable, 100);
}

@Override
public void onStopped() {
mHandler.removeCallbacks(runnable);
}
};

PlayerStateChangeListener mPlayerStateChangeListener = new PlayerStateChangeListener() {
@Override
public void onAdStarted() {
}

@Override
public void onError(ErrorReason arg0) {
}

@Override
public void onLoaded(String arg0) {
}

@Override
public void onLoading() {
}

@Override
public void onVideoEnded() {
}

@Override
public void onVideoStarted() {
displayCurrentTime();
}
};

SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
long lengthPlayed = (mPlayer.getDurationMillis() * progress) / 100;
mPlayer.seekToMillis((int) lengthPlayed);
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
};

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_video:
if (null != mPlayer && !mPlayer.isPlaying())
mPlayer.play();
break;
case R.id.pause_video:
if (null != mPlayer && mPlayer.isPlaying())
mPlayer.pause();
break;
}
}

private void displayCurrentTime() {
if (null == mPlayer) return;
String formattedTime = formatTime(mPlayer.getDurationMillis() – mPlayer.getCurrentTimeMillis());
mPlayTimeTextView.setText(formattedTime);
}

private String formatTime(int millis) {
int seconds = millis / 1000;
int minutes = seconds / 60;
int hours = minutes / 60;

return (hours == 0 ? “–:” : hours + “:”) + String.format(“%02d:%02d”, minutes % 60, seconds % 60);
}

private Runnable runnable = new Runnable() {
@Override
public void run() {
displayCurrentTime();
mHandler.postDelayed(this, 100);
}
};

}

nikeru8
nikeru8
5 years ago
Reply to  pronojit

take a look on this
The problem is only layout, the youtube player not permit anyone view stay over this, same invisible or transparent.

On way to discover this is with the developer option show layout boundaries.(warning with paddings and margins)
http://stackoverflow.com/questions/16067783/android-youtubeplayer-with-unauthorized-overlay-on-top-of-player

Nilanchala Panigrahy
Nilanchala Panigrahy
5 years ago

Thanks for pasting the solution her,e

Bambang Cahyo Soetrisno
Bambang Cahyo Soetrisno
5 years ago

How can I set default resolution 4K or HD?

swar
swar
4 years ago

thanxxx a lot!!!
it worked

swar
swar
4 years ago

how to show buffering progress

Tsormy
Tsormy
4 years ago

Thank you very much for the solution. I have been trying to integrate this in my app. I’m very new in this field. Can you please suggest how could I integrate it with simple listview/ recycler view options? I can show you the source code.

Ayaz khan
Ayaz khan
3 years ago

Hi How to move Seek bar forward Please help. seekBar.setProgress(progress); is not working

Mridul Shrivastava
Mridul Shrivastava
3 years ago

I am using default player style and I am fine with i, only thing I want to remove is “More Video” option which comes after finishing the video.
Anyone please can suggest me how I can achieve this without using PlayerStyle.CHROMELESS or PlayerStyle.MINIMAL?

Dharmendra
Dharmendra
2 years ago

How to add Landscape and Portrait Button and Speed option of youtube.Will you please Help me

Ishan
Ishan
2 years ago

We have done similar implementation.
In addition, does anyone know if we can put the “Playback Speed” control? I am not able to find anything for that. It is very helpful but can’t add it to custom controls as I couldn’t find any method for that.

Ahammed Irfan ali
Ahammed Irfan ali
2 years ago

How can I add full screen button to work on this

Previous Post
How to Configure Google Feedburner Feed for your Blog

How to Configure Google Feedburner Feed for your Blog

Next Post

Best Online Payment Services Alternative to PayPal

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
19
0
Would love your thoughts, please comment.x
()
x