Search code examples
androidgoogle-castchromecast

Displaying the MediaRouteButton for Chromecast in the action bar


The Netflix and YouTube apps supporting Chromecast show the MediaRouteButton in the action bar, but the Sender App Tutorial only shows how to display it in a layout. How do you display it in the action bar?


Solution

  • You can display it in the action bar by adding it to your action bar menu:

    <item
        android:id="@+id/action_mediaroute"
        android:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
        android:actionViewClass="android.support.v7.app.MediaRouteButton"
        android:showAsAction="always"
        android:title="@string/action_chromecast"/>
    

    Then you provide initialization in onCreateOptionsMenu:

    public boolean onCreateOptionsMenu( Menu menu ) {
    
        getMenuInflater().inflate( R.menu.main, menu );
    
        MenuItem mediaRouteItem = menu.findItem( R.id.action_mediaroute );
        mMediaRouteButton = (MediaRouteButton) mediaRouteItem.getActionView();
    
        mCastContext = new CastContext( getApplicationContext() );
        MediaRouteHelper.registerMinimalMediaRouteProvider( mCastContext, this );
        mMediaRouter = MediaRouter.getInstance( getApplicationContext() );
        mMediaRouteSelector = MediaRouteHelper.buildMediaRouteSelector( MediaRouteHelper.CATEGORY_CAST );
        mMediaRouteButton.setRouteSelector( mMediaRouteSelector );
        mMediaRouterCallback = new MyMediaRouterCallback();
    
        return true;
    }