1.design模式下,将TabLayout 拖入界面中
注意:TabLayout 在container中
2.design模式下,将ViewPager拖入界面中
<1>若出现错误(在xml文件中设置android:orientation="vertical")
<2>向viewpager中添加页面组件
(1)创建多个页面
app--->res--->layout ,选中layout,右击new--->xml--->layout xml file
(2)将多个页面布局添加到Viewpager中(采用Fragment的方式)
新建3个MyFragment(继承Fragment)
public class MyFragment1 extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.layout_page1,container,false); return view; }
3.源码
public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager viewPager; List<Fragment> fragments; //定义一个列表集合(应用泛型) String[] table={"新闻","财经","娱乐"}; //定义一个数组存放标题内容 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout=findViewById(R.id.tablayout); viewPager=findViewById(R.id.viewpager); fragments=new ArrayList<>(); //实例化集合 fragments.add(new MyFragment1()); fragments.add(new MyFragment2()); fragments.add(new MyFragment3()); Adapter adapter=new Adapter(getSupportFragmentManager(),fragments); //参数1为fragment管理器 viewPager.setAdapter(adapter); //给viewPager设置适配器 tabLayout.setupWithViewPager(viewPager); //将tabLayout与viewPager建立匹配 } //创建一个内部类作为适配器 public class Adapter extends FragmentPagerAdapter{ private List<Fragment> list; public Adapter(FragmentManager fm,List<Fragment> list) { super(fm); this.list=list; } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } //重写getPageTitle()方法,获取页标题 @Nullable @Override public CharSequence getPageTitle(int position) { return table[position]; } } }