Friday, December 16, 2016

TabLayout example

TabLayout in Android


First of all we have to add below code in dependencies,

compile 'com.android.support:design:25.0.1'

Below is the style.xml

<resources>

    <!-- Base application theme. -->    
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->        
<item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>



Then we have to add below code in activity_main.xml

<android.support.design.widget.CoordinatorLayout 
          xmlns:android="http://schemas.android.com/apk/res/android"    
          xmlns:app="http://schemas.android.com/apk/res-auto"    
          android:layout_width="match_parent"    
          android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout        
     android:layout_width="match_parent"        
     android:layout_height="wrap_content"        
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar            
         android:id="@+id/toolbar"            
         android:layout_width="match_parent"            
         android:layout_height="?attr/actionBarSize"            
         android:background="?attr/colorPrimary"            
         app:layout_scrollFlags="scroll|enterAlways"            
         app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout            
         android:id="@+id/tabLayout"            
         android:layout_width="match_parent"            
         android:layout_height="wrap_content"            
         app:tabMode="fixed"            
         app:tabGravity="fill"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"        
        android:layout_width="match_parent"        
        android:layout_height="match_parent"        
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>

Create layout for Fragment.

1> fragment_first.xml
<?xml version="1.0" 
  encoding="utf-8"?>
  <LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"    
   android:orientation="vertical" 
   android:layout_width="match_parent"    
   android:layout_height="match_parent">
    <TextView        
     android:layout_width="wrap_content"        
     android:layout_height="wrap_content"        
     android:text="This is first fragment"        
     android:textColor="@android:color/holo_blue_bright"        
     android:textSize="20sp"         
     android:gravity="center"        
     android:layout_gravity="center_horizontal"        />


</LinearLayout>

Now create FirstFrament class.

public class FirstFragment extends Fragment {

    private View v;

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args = getArguments();
        v = inflater.inflate(R.layout.fragment_first, container, false);
        return v;
    }
}

and create SecondFragment class & ThirdFragment class same as above.

Below code is ActivityMain.java class

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private TextView tvTitle;
    public static int currentTab;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getId();
        setViewPager();
        setTabIcon();


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override            public void onTabSelected(TabLayout.Tab tab) {

                // On third tab we have pass intent to call SecondActivity.

                Log.e("tab ","onTabSelected ===>"+tab.getPosition());
                currentTab = tab.getPosition();
                if(tab.getPosition()==2) {
                    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                    startActivity(intent);
                }
            }
            @Override            public void onTabUnselected(TabLayout.Tab tab) {
                Log.e("tab ","onTabUnselected ===>"+tab.getPosition());
            }
            @Override            public void onTabReselected(TabLayout.Tab tab) {
                Log.e("tab ","onTabReselected ===>"+tab.getPosition());
            }
        });
    }

    private void setViewPager() {
        // set Adaapter.

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),MainActivity.this);
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void getId() {
        try {
            tabLayout = (TabLayout) findViewById(R.id.tabLayout);
            viewPager = (ViewPager) findViewById(R.id.viewPager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // set custom icon to tab in Tablayout.

    private void setTabIcon() {
//        // First Tab

        View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_one_icon, null);
        tvTitle = (TextView) firstTab.findViewById(R.id.tvOne);
        tvTitle.setText("First Tab");
        tabLayout.getTabAt(0).setCustomView(firstTab);

        // Second Tab

        View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_two_icom, null);
        tvTitle = (TextView) secondTab.findViewById(R.id.tvTwo);
        tvTitle.setText("Second Tab");
        tabLayout.getTabAt(1).setCustomView(secondTab);

        //Third Tab

        View thirdTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_three_icon, null);
        tvTitle = (TextView) thirdTab.findViewById(R.id.tvThree);
        tvTitle.setText("Third Tab");
        tabLayout.getTabAt(2).setCustomView(thirdTab);
    }


    @Override    protected void onResume() {
        super.onResume();
        // here in Tab2 we have pass SecondActivity so if we beck from secondActivity then set it to tab 1.        
         if(currentTab==2){
            viewPager.setCurrentItem(1);
        }
    }



    public class ViewPagerAdapter  extends FragmentStatePagerAdapter {

        private Context context;

        public ViewPagerAdapter(FragmentManager fm, MainActivity mainActivity) {
            super(fm);
            context = mainActivity;
            new FirstFragment();
        }

        @Override        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    FirstFragment firstFragment = new FirstFragment();
                    return firstFragment;

                case 1:
                SecondFragment secondFragment= new SecondFragment ();
                return secondFragment;

                case 2:
                    FirstFragment firstFragment1 = new FirstFragment();
                    return firstFragment1;
                default:
                    return null;
            }
        }

        @Override        public int getCount() {
            return 3;
        }

        @Override        public CharSequence getPageTitle(int position) {
            return " " + position;
        }
    }
}

and we have csutomized tab icon and name so we need to define custom xml in layout folder like below  tab_three_icon


<?xml version="1.0" encoding="utf-8"?><LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"    
android:orientation="vertical" 
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:gravity="center"    >

    <ImageView        
     android:id="@+id/ivIcon"        
      android:layout_width="30dp"        
      android:layout_height="30dp"        
      android:background="@drawable/start_background"        
      android:layout_gravity="center_horizontal"/>

    <TextView        
     android:id="@+id/tvThree"        
     android:layout_width="wrap_content"        
     android:layout_height="wrap_content"        
     android:text="sakljaskljaskljsaklasjkl"        
     android:layout_gravity="center_vertical"        
     android:layout_marginLeft="10dp"/>


</LinearLayout>



and background of custom image view (ivIcon) of tab is.


<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"        
        android:drawable="@drawable/start_selected" />

    <item
        android:state_selected="false"        
        android:drawable="@drawable/star_unselect" />

</selector>

and in SecondFragment we have  created nested Fragment which containt two tab so layout of this fragment is

second_fragment.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"    
android:orientation="vertical"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:gravity="center">


    <android.support.design.widget.AppBarLayout        
     android:layout_width="match_parent"        
     android:layout_height="wrap_content"        
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.TabLayout            
         android:id="@+id/tabLayout"            
         android:layout_width="match_parent"            
         android:layout_height="wrap_content"            
         app:tabMode="fixed"            
         app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager        
     android:id="@+id/viewPager"        
     android:layout_width="match_parent"        
     android:layout_height="match_parent"        
     app:layout_behavior="@string/appbar_scrolling_view_behavior"  />


</LinearLayout>


SecondFragment code id blow.

public class SecondFragment  extends Fragment {

    private View v;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private TextView tvTitle;

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args = getArguments();

        v = inflater.inflate(R.layout.fragment_second, container, false);

        getIds();
        setViewPager();
        setTabIcon();

        return v;
    }
    private void getIds() {
        try {
            tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
            viewPager = (ViewPager) v.findViewById(R.id.viewPager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // set custom icon to tab in Tablayout.

    private void setTabIcon() {
//        // First Tab

        View firstTab = (View) LayoutInflater.from(getActivity()).inflate(R.layout.tab_one_icon, null);
        tvTitle = (TextView) firstTab.findViewById(R.id.tvOne);
        tvTitle.setText("Sub One");
        tabLayout.getTabAt(0).setCustomView(firstTab);

        // Second Tab

        View secondTab = (View) LayoutInflater.from(getActivity()).inflate(R.layout.tab_two_icom, null);
        tvTitle = (TextView) secondTab.findViewById(R.id.tvTwo);
        tvTitle.setText("Sub Two");
        tabLayout.getTabAt(1).setCustomView(secondTab);

    }

    private void setViewPager() {
        // set Adaapter.

        viewPagerAdapter = new ViewPagerAdapter(getFragmentManager(), (MainActivity) getActivity());
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }


    public class ViewPagerAdapter  extends FragmentStatePagerAdapter {

        private Context context;

        public ViewPagerAdapter(FragmentManager fm, MainActivity mainActivity) {
            super(fm);
            context = mainActivity;
        }

        @Override        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    SubFragOne subFragOne = new SubFragOne();
                    return subFragOne;

                case 1:
                    SubFragTwo subFragTwo= new SubFragTwo();
                    return subFragTwo;
                default:
                    return null;
            }
        }

        @Override        public int getCount() {
            return 2;
        }

        @Override        public CharSequence getPageTitle(int position) {
            return " " + position;
        }
    }

}


For more detail check Tablayout_28_11_2016 demo

1 comment: