TabLayout简单的使用
程序员文章站
2022-06-01 15:14:59
...
效果图:
项目结构图:
代码的实现:
1.在应用的build.gradle中添加support:design支持库
compile 'com.android.support:design:25.0.0'
2.在xml文件里添加布局TabLayout和ViewPager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3000">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</LinearLayout>
3.创建ViewPager适配器SimpleFragmentPagerAdapter
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
String s[];
Context context;
ArrayList<Fragment> f=new ArrayList<>();
//重写构造方法
public SimpleFragmentPagerAdapter(FragmentManager fm,ArrayList<Fragment> f,String s[],Context context) {
super(fm);
this.context=context;
this.f=f;
this.s=s;
}
@Override
public Fragment getItem(int position) {
return f.get(position);
}
@Override
public int getCount() {
return s.length;
}
@Override
public CharSequence getPageTitle(int position) {
return s[position];
}
}
urn s[position];
}
}
4.在MainActivity里实现:
public class MainActivity extends AppCompatActivity {
ArrayList<Fragment> f=new ArrayList<>();
String s[]={"f1","f2","f3"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
//new出3个Fragment
PageFragment pageFragment = new PageFragment();
PageFragment2 pageFragment2 = new PageFragment2();
PageFragment3 pageFragment3 = new PageFragment3();
//往集合添加Fragmgnt
f.add(pageFragment);
f.add(pageFragment2);
f.add(pageFragment3);
//实现适配器传4个参数,第一个是碎片管理器,第二个是存Fragment的集合,第三个是标题的数组,第四个是上下文
SimpleFragmentPagerAdapter simpleFragmentPagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(),f,s, this);
ViewPager vp = (ViewPager) findViewById(R.id.vp);
//ViewPager添加适配器
vp.setAdapter(simpleFragmentPagerAdapter);
TabLayout tab = (TabLayout) findViewById(R.id.tab);
//TabLayout添加ViewPager
tab.setupWithViewPager(vp);
//设置TabLayout模式
tab.setTabMode(TabLayout.MODE_FIXED);
}
}
上一篇: TabLayout的使用
下一篇: TabLayout的简单使用