package com.example.toutiao; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; public class MyTabLayout extends AppCompatActivity { private TabLayout tablayout; private ViewPager vp; private ArrayList<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab_layout); //初始化控件 tablayout = (TabLayout) findViewById(R.id.tablayout); vp = (ViewPager) findViewById(R.id.vp); //创建集合向集合中添加导航数据 list = new ArrayList<String>(); list.add("头条"); list.add("社会"); list.add("国内"); list.add("国际"); list.add("娱乐"); list.add("体育"); list.add("军事"); list.add("科技"); list.add("财经"); list.add("时尚"); //设置适配器 vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { //在此重写此方法得到当前页面的标题 //也就是设置tab对应的标题 @Override public CharSequence getPageTitle(int position) { return list.get(position); } //在此方法中动态添加fragment @Override public Fragment getItem(int position) { NewsFragment newsFragment = new NewsFragment(); Bundle bundle = new Bundle(); //判断当前的导航显示的数据来向Bundle对象中添加相应的数据 if (list.get(position).equals("头条")){ bundle.putString("name","top"); }else if (list.get(position).equals("社会")){ bundle.putString("name","shehui"); }else if (list.get(position).equals("国内")){ bundle.putString("name","guonei"); }else if (list.get(position).equals("国际")){ bundle.putString("name","guoji"); }else if (list.get(position).equals("娱乐")){ bundle.putString("name","yule"); }else if (list.get(position).equals("体育")){ bundle.putString("name","tiyu"); }else if (list.get(position).equals("军事")){ bundle.putString("name","junshi"); }else if (list.get(position).equals("科技")){ bundle.putString("name","keji"); }else if (list.get(position).equals("财经")){ bundle.putString("name","caijing"); }else if (list.get(position).equals("时尚")){ bundle.putString("name","shishang"); } //给fragment 加bundle 数据 //activity与fragment 1.getset,2.接口回调,3.setArguments ,getAraguments newsFragment.setArguments(bundle); return newsFragment; } @Override public int getCount() { return list.size(); } }); //设置tablayout和ViewPager关联(此代码是整个项目的核心) tablayout.setupWithViewPager(vp); } }