Tablayout和ViewPager实现今日头条Tablayout

依赖:

compile 'com.android.support:design:26.0.0-alpha1'

布局:

activity_main:



    

    


代码页面:

MainActivity页面:

public class MainActivity extends AppCompatActivity {
    private TabLayout tablayout;
    private ViewPager viewPager;
    //数据源
    private String[] titles = {"头条", "新闻", "娱乐", "体育", "美女", "科技", "财经", "汽车", "彩票", "国际", "推荐",};

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


        tablayout = (TabLayout) findViewById(R.id.tablayout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
        viewPager.setAdapter(myPagerAdapter);

        tablayout.setupWithViewPager(viewPager);

        //每条之间的分割线
        LinearLayout linearLayout = (LinearLayout) tablayout.getChildAt(0);

        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);

        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this,
                R.drawable.layout_divider_vertical));

        //如果要在顶上加入图片
//        for (int i = 0; i < tablayout.getTabCount(); i++) {
//            TabLayout.Tab tab = tablayout.getTabAt(i);
//            tab.setIcon(R.mipmap.ic_launcher);
//        }
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public Fragment getItem(int position) {
            TestFragment testFragment = new TestFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title", titles[position]);
            testFragment.setArguments(bundle);
            return testFragment;
        }

        @Override
        public int getCount() {
            return titles.length;
        }
    }
}

TestFragment页面:
public class TestFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_layout, container, false);
        TextView textView = (TextView) view.findViewById(R.id.title);
        String name = this.getArguments().getString("title");
        textView.setText(name);
        return view;
    }

}
drawable文件夹下创建
layout_divider_vertical:




你可能感兴趣的:(Tablayout和ViewPager实现今日头条Tablayout)