TabLayout + ViewPager 定制导航条(1)

刚开始学习android不久,像iOS中的Tabbar那么简单的东西到android里却并没有特别方便现成的实现。查阅了好多博客网站,各种各样的方式五花八门,有些大神代码给的也不甚全,所以先决定参考下面的教程用TabLayout + ViewPager来做一个再说吧。

Google Play Style Tabs using TabLayout

先新建一个工程吧,把activity_main.xml修改如下:




    

    

然后,再来把Fragment搞定,先随便弄一个fragment_page.xml, 用一个textView来区分不同的Fragment即可:



定义一个Fragment类:

public class PageFragment extends Fragment {

    public static final String ARG_PAGE = "ARG_PAGE";
    private int mPage;

    public static PageFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        PageFragment fragment = new PageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);
    }

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

        View view = inflater.inflate(R.layout.fragment_page, container, false);
        TextView textView = (TextView) view;
        textView.setText("Fragment #" + mPage);
        return view;
    }
}

接下来,我们给ViewPager自定义一个Adapter

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {

    final int PAGE_COUNT = 3;
    private String tabTitles[] = new String[] {"Tab1", "Tab2", "Tab3"};
    private Context mContext;

    // 自己随便找三张图片放在drawable下
    private int[] imageResId = {
                R.drawable.tab_home,
                R.drawable.tab_discovery,
                R.drawable.tab_profile
    };

    public SampleFragmentPagerAdapter(FragmentManager manager, Context context) {
        super(manager);
        this.mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        return PageFragment.newInstance(position + 1);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
}

这个adapter很简单,主要提供fragment和title.

最后就是MainActivity.class

public class MainActivity extends AppCompatActivity {

    public static String POSITION = "POSITION";

    private TabLayout mTabLayout;
    private ViewPager mViewPager;


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

        mViewPager = findViewById(R.id.viewPager);
        final SampleFragmentPagerAdapter pagerAdapter = new SampleFragmentPagerAdapter(getSupportFragmentManager(), MainActivity.this);
        mViewPager.setAdapter(pagerAdapter);

        mTabLayout = findViewById(R.id.sliding_tabs);
        mTabLayout.setupWithViewPager(mViewPager);
    }
}

这样,一个简单的导航条就完成了:


TabLayout + ViewPager 定制导航条(1)_第1张图片
效果图

你可能感兴趣的:(TabLayout + ViewPager 定制导航条(1))