-
-
Save jesselima/023206311685600e206fe641cf13d43a to your computer and use it in GitHub Desktop.
Android Sliding TabLayout with Icons.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.simpletablayout; | |
import android.os.Bundle; | |
import android.support.annotation.Nullable; | |
import android.support.design.widget.TabLayout; | |
import android.support.v4.app.Fragment; | |
import android.support.v4.app.FragmentManager; | |
import android.support.v4.app.FragmentPagerAdapter; | |
import android.support.v4.view.ViewPager; | |
import android.support.v7.app.AppCompatActivity; | |
import java.util.ArrayList; | |
import java.util.List; | |
import fragments.base.Home; | |
import fragments.base.Profile; | |
import fragments.base.Setting; | |
public class SimpleTabLayout extends AppCompatActivity { | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_tablayout); | |
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); | |
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); | |
//Add tabs icon with setIcon() or simple text with .setText() | |
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_home)); | |
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_profile)); | |
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_settings)); | |
//Add fragments | |
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager()); | |
adapter.addFragment(new Home()); | |
adapter.addFragment(new Profile()); | |
adapter.addFragment(new Setting()); | |
//Setting adapter | |
viewPager.setAdapter(adapter); | |
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); | |
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager)); | |
} | |
class PagerAdapter extends FragmentPagerAdapter { | |
private final List<Fragment> mFragments = new ArrayList<>(); | |
public PagerAdapter(FragmentManager fm) { | |
super(fm); | |
} | |
public void addFragment(Fragment fragment) { | |
mFragments.add(fragment); | |
} | |
@Override | |
public Fragment getItem(int position) { | |
return mFragments.get(position); | |
} | |
@Override | |
public int getCount() { | |
return mFragments.size(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment