Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to Implement TabLayout with Icon in Android?

How to Implement TabLayout with Icon in Android?

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
    xmlns:tools="http://schemas.android.com/tools"
    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
    xmlns:tools="http://schemas.android.com/tools"
    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:

 

 

RELATED ARTICLES

Most Popular

Recent Comments