Add Swipe Tabs inside Navigation Drawer in Android

In this tutorial, we are going to learn how to add swipe tabs inside navigation drawer in android. This tutorial is part of a future tutorial where we will learn how to create Android Music Player.

But right now lets focus on how to add swipe tabs inside navigation drawer in android. In some of my tutorials, I have covered topics related to android swipe tabs and navigation drawer. If you are interested you can read them from the links below.

1. Android Swipe Tabs with ViewPager

2. Understanding Android ViewPager and PageAdapter 

3. How to Combine Navigation Drawer with Master Detail Flow in Android 

For this example, we are going to create an intro page, navigation drawer activity page which will use a single Fragment class for each of its menu items. Inside the home Fragment, we will add a sub-fragment with TabLayout. The TabLayout will be setup with a View pager which will use a PageAdapter to manage Fragments for each tab menu.

If the whole project description sounds complicated, don’t worry. By the time we deconstruct it, everything will appear very easy to understand.

In other to get a visual understanding of what we are going to create in this android tutorial, I have add below some screen shots from the application.

SOME SCREENSHOT FROM THE APPLICATION

android music player androidmusicplayer2

CREATE NEW ANDROID PROJECT

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 24

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidMusicPlayer

Package: com.inducesmile.androidmusicplayer

Select Empty Activity

Name your activity: SplashActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Add Library Dependencies in Build.gradle

Lets open the module build.gradle file, we are going to add some third party libraries in our project. Using good third party library can increase productivity and save development time. Also it help so that we will reinvent the wheels.

Open this file and add the dependencies below.

apply plugin: 'com.android.application'
apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androidmusicplayer"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.intuit.sdp:sdp-android:1.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.android.support:support-v4:25.0.0'
    testCompile 'junit:junit:4.12'
}

Follow this project structure or use your own

We are going to restructure our project in a way to make it easy to know where to look for any file we have created. This is not the best way to do it but for the seek of this tutorial I am using the structure as it appears on the image below.

You can see that I have created three package – adapter, entities and fragment.

android project structure

STRINGS.XML

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<resources>
    <string name="app_name">Android Music Player</string>
    <string name="title_activity_music">Music Home</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="action_settings">Settings</string>
    <string name="adele_hello">Adele - Hello</string>
    <string name="music_library">Library</string>
    <string name="music_songs">Songs</string>
    <string name="music_playlists">Playlists</string>
    <string name="music_albums">Albums</string>
    <string name="music_artists">Artists</string>
    <string name="remote_services">Remote Services</string>
    <string name="sound_cloud">Sound Cloud</string>
    <string name="local_services">Local Services</string>
    <string name="app_raw_folder">App raw folder</string>
    <!-- TODO: Remove or change this placeholder text -->
    <string name="hello_blank_fragment">Hello blank fragment</string>
    <string name="recently_played_songs">Recently Played Songs</string>
    <string name="hello">Someone Like You</string>
    <string name="adele">Adele</string>
    <string name="your_playlists">Your Playlists</string>
    <string name="let_me_go">Let Me Go</string>
</resources>

COLORS.XML

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#b7a676</color>
    <color name="colorPrimaryDark">#988a62</color>
    <color name="colorAccent">#a9cf54</color>
    <color name="colorDarker">#d3c498</color>
    <color name="colorLighter">#FFF4D1</color>
    <color name="colorBlack">#000000</color>
    <color name="colorWhite">#ffffff</color>
</resources>

 Dimens.xml

while still inside the values folder, open the dimens.xml file and replace the content with the code below.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">256dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
</resources>

 SplashActivity.java and activity_splash.xml

When our android project was created, Android Studio created a default activity page with its corresponding layout file for us. If you remember we name this activity class SplashActivity.java.

This will serve as an intro splash page. You can omit it if it will not fit in your project requirements.

activity_splash.xml

Open the activity_splash.xml and add the code below. This layout file contains a logo image for the app.

<?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:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/colorPrimaryDark"
    tools:context="com.inducesmile.androidmusicplayer.SplashActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="16dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/logomusic"
            android:contentDescription="@string/app_name"/>
    </LinearLayout>
</LinearLayout>

Remember to replace all the images resources in the layout files with your own images. You can as well have access to the images when you download the application source code.

SplashActivity Class

The SplashActivity uses a postDelay of 3 seconds before it navigation to the main app screen. Open the file and add the code below.

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class SplashActivity extends AppCompatActivity {
    private static final String TAG = SplashActivity.class.getSimpleName();
    private final int SPLASH_DISPLAY_LENGTH = 3000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ActionBar actionBar = getSupportActionBar();
        if(null != actionBar){
            actionBar.hide();
        }
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run(){
                Intent startActivityIntent = new Intent(SplashActivity.this, MusicActivity.class);
                startActivity(startActivityIntent);
                SplashActivity.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}

 Create Navigation Drawer Activity

Now, create a new activity class. Choose the Navigation Drawer Activity option. Name the activity file MusicActivity.java.

Android Studio will create the MusicActivity class, four layout files and a menu item layout file. We will go through each of them and make changes as we go.

activity_music.xml

Open the activity_music.xm and modify the code as shown below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_music"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/activity_music_drawer" />
</android.support.v4.widget.DrawerLayout>

 app_bar_music.xml

Open the app_bar_music.xml file and modify the code as shown below

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.inducesmile.androidmusicplayer.MusicActivity">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
    <include layout="@layout/content_music" />
</android.support.design.widget.CoordinatorLayout>

content_music.xml

Open the content_music.xml file and modify the code as shown below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.inducesmile.androidmusicplayer.MusicActivity">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
    <include layout="@layout/content_music" />
</android.support.design.widget.CoordinatorLayout>

 nav_header_music.xml

Open the nav_header_music.xml file and modify the code as shown below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navigation_header"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@color/colorPrimaryDark"
    android:gravity="bottom"
    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"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
    
     <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="@dimen/_100sdp"
        android:layout_height="@dimen/_100sdp"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/_8sdp"
        android:src="@drawable/adele"
        android:id="@+id/circleView"/>
   
    <TextView
        android:id="@+id/profile_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/_8sdp"
        android:textSize="@dimen/_16sdp"
        android:text="@string/adele_hello"
        android:layout_gravity="center"
        android:textColor="@color/colorWhite"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

</LinearLayout>

 MusicActivity.java

In the MusicActivity class, we are going to get the instances of the DrawerLayout and NavigationView.

We will create a an instance of FragmentManager which we will use to manage individual Fragment object that is associated with each menu item.

Inside the setNavigationItemSelectedListeter() method, add the Fragment instance of the Library menu item like this

if (id == R.id.nav_library) {
    fragment = new LibraryFragment();
}

Open the MusicActivity class and modify the code as shown below

import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.inducesmile.androidmusicplayer.fragment.LibraryFragment;
import com.inducesmile.androidmusicplayer.fragment.PlaylistFragment;
public class MusicActivity extends AppCompatActivity{
    private static final String TAG = MusicActivity.class.getSimpleName();
    private FragmentManager fragmentManager;
    private Fragment fragment = null;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        fragmentManager = getSupportFragmentManager();
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragment = new LibraryFragment();
        fragmentTransaction.replace(R.id.main_container_wrapper, fragment);
        fragmentTransaction.commit();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View header = navigationView.inflateHeaderView(R.layout.nav_header_music);
        TextView profileName = (TextView) header.findViewById(R.id.profile_name);
        profileName.setText("Adele");
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                int id = item.getItemId();
                if (id == R.id.nav_library) {
                    fragment = new LibraryFragment();
                } else if (id == R.id.nav_song) {
                    fragment = new PlaylistFragment();
                } else if (id == R.id.nav_playlist) {
                } else if (id == R.id.nav_sound_cound) {
                }else if (id == R.id.nav_raw_folder) {
                }
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.main_container_wrapper, fragment);
                transaction.commit();
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                assert drawer != null;
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }
        });
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.music, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

 Modify Menu Drawer Layout

When Android Studio generated the Navigation Drawer template for us, it also add a menu folder in the res folder.

Open the menu folder inside the res folder, double click on activity_music_drawer.xml and modify the content as below.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/one" android:checkableBehavior="single">
        <item
            android:id="@+id/nav_library"
            android:icon="@drawable/ic_menu_camera"
            android:title="@string/music_library" />
    </group>
    <group android:id="@+id/two" android:checkableBehavior="single">
        <item
            android:id="@+id/nav_song"
            android:icon="@drawable/ic_menu_gallery"
            android:title="@string/music_songs" />
    </group>
    <group android:id="@+id/three" android:checkableBehavior="single">
        <item
            android:id="@+id/nav_playlist"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="@string/music_playlists" />
    </group>
    <item android:title="@string/remote_services">
        <menu>
            <item
                android:id="@+id/nav_sound_cound"
                android:icon="@drawable/ic_menu_camera"
                android:title="@string/sound_cloud" />
        </menu>
    </item>
    <item android:title="@string/local_services">
        <menu>
            <item
                android:id="@+id/nav_raw_folder"
                android:icon="@drawable/ic_menu_camera"
                android:title="@string/app_raw_folder" />
        </menu>
    </item>
</menu>

 Creating a Swipe Tab inside the Navigation Drawer

Since we have done with creating our navigation drawer, the next step is to learn how to add a swipe tabs inside the navigation drawer.

If you look at our MusicActivity class, you will see that in first menu item uses LibraryFragment class as its own page.

We are going to create this Fragment and add a TabLayout in its layout file.

LibraryFragment.java

Create a new Fragment file and name it LibraryFragment.java. Open the layout file associated with LibraryFragment and add a ViewPager and TabLyout as shown below

fragment_library.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.inducesmile.androidmusicplayer.fragment.LibraryFragment">
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:padding="@dimen/_6sdp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"/>
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>

In the LibraryFragment class, get the instances of the TabLayout and ViewPager. We will create a new PageAdapter to the ViewPager later but for now lets call it CustomFragmentPageAdapter.java.

Call the setupWithViewPager() method of the TabLayout class and pass the ViewPager object as a parameter to the method.

The complete code for the LibraryFragment class as shown below

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.inducesmile.androidmusicplayer.R;
import com.inducesmile.androidmusicplayer.adapter.CustomFragmentPageAdapter;
public class LibraryFragment extends Fragment {
    private static final String TAG = LibraryFragment.class.getSimpleName();
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LibraryFragment() {
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_library, container, false);
        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.view_pager);
        viewPager.setAdapter(new CustomFragmentPageAdapter(getChildFragmentManager()));
        tabLayout.setupWithViewPager(viewPager);
        return view;
    }
}

 Create a new PageAdaper

Create a new PageAdapter class which will inherit from the FragmentPageAdapter. Name the class CustomFragmentPageAdapter.java.

This class will be use to bind the each page of the ViewPager. Each page will contain a Fragment class.

The following methods are overridden when you inherits from a PageAdapter.

getItem(int position);

getCount();

getCount() method returns the number of pages to display. in the getItem(int position), we will create individual Fragment class.

Open the CustomFragmentPageAdapter class and add the code below

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.inducesmile.androidmusicplayer.fragment.PlaylistFragment;
import com.inducesmile.androidmusicplayer.fragment.SongFragment;
public class CustomFragmentPageAdapter extends FragmentPagerAdapter{
    private static final String TAG = CustomFragmentPageAdapter.class.getSimpleName();
    private static final int FRAGMENT_COUNT = 4;
    public CustomFragmentPageAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new SongFragment();
            case 1:
                return new PlaylistFragment();
        }
        return null;
    }
    @Override
    public int getCount() {
        return FRAGMENT_COUNT;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            case 0:
                return "Songs";
            case 1:
                return "Playlists";
            case 2:
                return "Albums";
            case 3:
                return "Artists";
        }
        return null;
    }
}

 Create Fragment Classes for the PageAdapter

You can see from the getItem(int position) method in the PageAdapter class we are going to use two Fragment class – (SongFragment.java and PlaylistFragment.java).

First create a the SongFrament class which will inherit from a Fragment class. Its layout file will contain TextView and RecyclerView widgets. Open the layout file and add the code below.

fragment_song.xml

<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:background="@drawable/bg"
    tools:context="com.inducesmile.androidmusicplayer.fragment.SongFragment">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/recently_played_songs"
        android:padding="@dimen/_16sdp"
        android:textSize="@dimen/_13sdp"
        android:textColor="@color/colorWhite"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/song_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scrollbars="none" />
</LinearLayout>

 SongFragment.java

For the SongFragment class, get the instance of the RecyclerView. We will create another RecyclerView adapter that will bind its data source to its list items.

Open the SongFragment class and add the code below

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.inducesmile.androidmusicplayer.R;
import com.inducesmile.androidmusicplayer.adapter.SongAdapter;
import com.inducesmile.androidmusicplayer.entities.SongObject;
import java.util.ArrayList;
import java.util.List;
public class SongFragment extends Fragment {
    public SongFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_song, container, false);
        getActivity().setTitle("Songs");
        RecyclerView songRecyclerView = (RecyclerView)view.findViewById(R.id.song_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        songRecyclerView.setLayoutManager(linearLayoutManager);
        songRecyclerView.setHasFixedSize(true);
        SongAdapter mAdapter = new SongAdapter(getActivity(), getTestData());
        songRecyclerView.setAdapter(mAdapter);
        return view;
    }
    public List<SongObject> getTestData() {
        List<SongObject> recentSongs = new ArrayList<SongObject>();
        recentSongs.add(new SongObject("Adele", "Someone Like You", ""));
        recentSongs.add(new SongObject("Adele", "Someone Like You", ""));
        recentSongs.add(new SongObject("Adele", "Someone Like You", ""));
        recentSongs.add(new SongObject("Adele", "Someone Like You", ""));
        recentSongs.add(new SongObject("Adele", "Someone Like You", ""));
        recentSongs.add(new SongObject("Adele", "Someone Like You", ""));
        return recentSongs;
    }
}

 Create Adapter for RecyclerView Widget in SongFragment Class

We will create a RecyclerView adapter class and ViewHolder class. Create two java classes and name them SongAdapter.java and SongViewHolder.java. Open each file and add the code below.

SongAdapter.java

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.inducesmile.androidmusicplayer.R;
import com.inducesmile.androidmusicplayer.entities.SongObject;
import java.util.List;
public class SongAdapter extends RecyclerView.Adapter<SongViewHolder>{
    private Context context;
    private List<SongObject> allSongs;
    public SongAdapter(Context context, List<SongObject> allSongs) {
        this.context = context;
        this.allSongs = allSongs;
    }
    @Override
    public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.song_list_layout, parent, false);
        return new SongViewHolder(view);
    }
    @Override
    public void onBindViewHolder(SongViewHolder holder, int position) {
        SongObject songs = allSongs.get(position);
        holder.songTitle.setText(songs.getSongTitle());
        holder.songAuthor.setText(songs.getSongAuthor());
    }
    @Override
    public int getItemCount() {
        return allSongs.size();
    }
}

 SongViewHolder.java

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.inducesmile.androidmusicplayer.R;
public class SongViewHolder extends RecyclerView.ViewHolder{
    public TextView songTitle;
    public TextView songAuthor;
    public ImageView songImage;
    public SongViewHolder(View itemView, TextView songTitle, TextView songAuthor, ImageView songImage) {
        super(itemView);
        this.songTitle = songTitle;
        this.songAuthor = songAuthor;
        this.songImage = songImage;
    }
    public SongViewHolder(View itemView) {
        super(itemView);
        songTitle = (TextView)itemView.findViewById(R.id.song_title);
        songAuthor = (TextView)itemView.findViewById(R.id.song_author);
        songImage = (ImageView)itemView.findViewById(R.id.song_cover);
    }
}

 Create the Second Tab Fragment – PlaylistFragment.java

Create a Fragment as above and name it PlaylistFragment.java. Open the file and add the code below.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.inducesmile.androidmusicplayer.R;
import com.inducesmile.androidmusicplayer.adapter.PlaylistAdapter;
import com.inducesmile.androidmusicplayer.entities.PlaylistObject;
import java.util.ArrayList;
import java.util.List;
public class PlaylistFragment extends Fragment {
    public PlaylistFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_playlist, container, false);
        RecyclerView playlisRecyclerView = (RecyclerView)view.findViewById(R.id.your_play_list);
        GridLayoutManager gridLayout = new GridLayoutManager(getActivity(), 2);
        playlisRecyclerView.setLayoutManager(gridLayout);
        playlisRecyclerView.setHasFixedSize(true);
        PlaylistAdapter mAdapter = new PlaylistAdapter(getActivity(), getTestData());
        playlisRecyclerView.setAdapter(mAdapter);
        return view;
    }
    public List<PlaylistObject> getTestData() {
        List<PlaylistObject> trackList = new ArrayList<PlaylistObject>();
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        trackList.add(new PlaylistObject("Falling over", "12 tracks", ""));
        return trackList;
    }
}

 fragment_playlist.xml

<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:background="@drawable/bg"
    tools:context="com.inducesmile.androidmusicplayer.fragment.PlaylistFragment">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/your_playlists"
        android:padding="@dimen/_16sdp"
        android:textSize="@dimen/_13sdp"
        android:textColor="@color/colorWhite"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/your_play_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="@dimen/_4sdp"
        android:scrollbars="none" />
</LinearLayout>

 Create Adapter for RecyclerView Widget in PlaylistFragment Class

We will create a RecyclerView adapter class and ViewHolder class. Create two java classes and name them PlaylistAdapter.java and PlaylistViewHolder.java. Open each file and add the code below.

PlaylistAdapter.java

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.inducesmile.androidmusicplayer.R;
import com.inducesmile.androidmusicplayer.entities.PlaylistObject;
import java.util.List;
public class PlaylistAdapter extends RecyclerView.Adapter<PlaylistViewHolder>{
    private static final String TAG = PlaylistAdapter.class.getSimpleName();
    private Context context;
    private List<PlaylistObject> playlists;
    public PlaylistAdapter(Context context, List<PlaylistObject> playlists) {
        this.context = context;
        this.playlists = playlists;
    }
    @Override
    public PlaylistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.play_list_layout, parent, false);
        return new PlaylistViewHolder(view);
    }
    @Override
    public void onBindViewHolder(PlaylistViewHolder holder, int position) {
        PlaylistObject playlistObject = playlists.get(position);
        holder.playlistTitle.setText(playlistObject.getPlaylistTitle());
        holder.playlistTracks.setText(playlistObject.getPlaylistTracks());
    }
    @Override
    public int getItemCount() {
        return playlists.size();
    }
}

 PlaylistViewHolder.java

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.inducesmile.androidmusicplayer.R;
public class PlaylistViewHolder extends RecyclerView.ViewHolder{
    public TextView playlistTitle;
    public TextView playlistTracks;
    public ImageView playlistCover;
    public PlaylistViewHolder(View itemView) {
        super(itemView);
        playlistTitle = (TextView)itemView.findViewById(R.id.play_list_name);
        playlistTracks = (TextView)itemView.findViewById(R.id.number_of_tracks);
        playlistCover = (ImageView)itemView.findViewById(R.id.play_list_cover);
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

This is part of the Android Music Player I am developing. If you will like to know how to develop beautiful android music player then stick with me.

I hope at this point you can create a swipe tabs inside navigation drawer in android.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.

23 Comments

    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile

Add a Comment