TabLayout is used to implement horizontal tabs. TabLayout is introduced in the design support library to implement tabs. Tabs are created using the newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout using the method addTab(Tab) method.
What we are going to build in this article?
In this article, we will make three separate tabs with their respective icons with the help of viewPager. A sample video of what we are going to build in this article is shown below. Note that we are going to implement this project in Java Language.
Step by Step Implementation
Step 1: Create a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Â
Step 2: Adding required dependency
Navigate to Gradle scripts > build.gradle(module) and the following dependency in it-
implementation 'com.google.android.material:material:1.2.1'
Step 3: Working on XML files
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity">Â
    <com.google.android.material.tabs.TabLayout        android:layout_width="match_parent"        android:layout_height="?actionBarSize"        android:id="@+id/tab_layout"        android:background="@color/white"        app:tabInlineLabel="true"        app:tabTextColor="@color/teal_700"        app:tabIndicatorColor="@color/teal_700"        app:tabSelectedTextColor="@color/teal_700"        app:tabTextAppearance="@style/TextAppearance.AppCompat.Small"/>       <androidx.viewpager.widget.ViewPager        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/view_pager"/>Â
</LinearLayout> |
Â
Â
Navigate to app > right-click  >  new > fragment > blank fragment. Name the fragment as MainFragment. Below is the code for fragment_main.xml file-
Â
XML
<?xml version="1.0" encoding="utf-8"?><FrameLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainFragment">Â
   <TextView       android:layout_width="match_parent"       android:layout_height="match_parent"       android:id="@+id/text_view"       android:textSize="32sp"       android:textStyle="bold"       android:gravity="center"/>Â
</FrameLayout> |
Â
Â
Step 4: Working on java files
Â
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.
Â
Java
package com.example.tablayoutwithicon;Â
import androidx.annotation.ContentView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.ContextCompat;import androidx.fragment.app.Fragment;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentPagerAdapter;import androidx.viewpager.widget.ViewPager;Â
import android.graphics.drawable.Drawable;import android.os.Bundle;import android.text.Spannable;import android.text.SpannableString;import android.text.Spanned;import android.text.style.ImageSpan;Â
import com.google.android.material.tabs.TabLayout;Â
import java.lang.reflect.Array;import java.util.ArrayList;Â
public class MainActivity extends AppCompatActivity {Â
    // Initialize variables    TabLayout tabLayout;    ViewPager viewPager;Â
    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);Â
        // assign variable        tabLayout=findViewById(R.id.tab_layout);        viewPager=findViewById(R.id.view_pager);Â
        // Initialize array list        ArrayList<String> arrayList=new ArrayList<>(0);Â
        // Add title in array list        arrayList.add("Basic");        arrayList.add("Advance");        arrayList.add("Pro");Â
        // Setup tab layout        tabLayout.setupWithViewPager(viewPager);Â
        // Prepare view pager        prepareViewPager(viewPager,arrayList);              }Â
    private void prepareViewPager(ViewPager viewPager, ArrayList<String> arrayList) {        // Initialize main adapter        MainAdapter adapter=new MainAdapter(getSupportFragmentManager());                 // Initialize main fragment        MainFragment mainFragment=new MainFragment();                 // Use for loop        for(int i=0;i<arrayList.size();i++)        {            // Initialize bundle            Bundle bundle=new Bundle();Â
            // Put title            bundle.putString("title",arrayList.get(i));Â
            // set argument            mainFragment.setArguments(bundle);Â
            // Add fragment            adapter.addFragment(mainFragment,arrayList.get(i));            mainFragment=new MainFragment();        }        // set adapter        viewPager.setAdapter(adapter);    }Â
    private class MainAdapter extends FragmentPagerAdapter {        // Initialize arrayList        ArrayList<Fragment> fragmentArrayList= new ArrayList<>();        ArrayList<String> stringArrayList=new ArrayList<>();Â
        int[] imageList={R.drawable.basic,R.drawable.advance,R.drawable.pro};Â
        // Create constructor        public void addFragment(Fragment fragment,String s)        {            // Add fragment            fragmentArrayList.add(fragment);            // Add title            stringArrayList.add(s);        }Â
        public MainAdapter(FragmentManager supportFragmentManager) {            super(supportFragmentManager);        }Â
        @NonNull        @Override        public Fragment getItem(int position) {            // return fragment position            return fragmentArrayList.get(position);        }Â
        @Override        public int getCount() {            // Return fragment array list size            return fragmentArrayList.size();        }Â
        @Nullable        @Override        public CharSequence getPageTitle(int position) {Â
            // Initialize drawable            Drawable drawable= ContextCompat.getDrawable(getApplicationContext()            ,imageList[position]);Â
            // set bound            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),                    drawable.getIntrinsicHeight());Â
            // Initialize spannable image            SpannableString spannableString=new SpannableString(""+stringArrayList.get(position));Â
            // Initialize image span            ImageSpan imageSpan=new ImageSpan(drawable,ImageSpan.ALIGN_BOTTOM);Â
            // Set span            spannableString.setSpan(imageSpan,0,1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);Â
            // return spannable string            return spannableString;        }    }} |
Â
Â
Go to the MainFragment.java file and refer to the following code. Below is the code for the MainFragment.java file.
Â
Java
package com.example.tablayoutwithicon;Â
import android.os.Bundle;Â
import androidx.fragment.app.Fragment;Â
import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;Â
public class MainFragment extends Fragment {    // Initialize variable    TextView textView;Â
    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Initialize view        View view =inflater.inflate(R.layout.fragment_main, container, false);Â
        // Assign variable        textView=view.findViewById(R.id.text_view);Â
        // Get Title        String sTitle=getArguments().getString("title");                 // Set title on text view        textView.setText(sTitle);Â
        // return view        return view;    }} |
Â
Â
Here is the final output of our application.
Â
Output:
Â
Â
