TabLayout+fragment
时间: 2024-01-11 09:04:10 浏览: 83
TabLayout是一种常见的Android UI控件,可以用于在Activity或Fragment中创建多个选项卡,每个选项卡可以加载不同的Fragment。下面是实现TabLayout和Fragment的步骤:
1. 在布局文件中添加TabLayout和ViewPager控件,如下所示:
```
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
2. 创建Fragment类,例如:
```
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
//TODO: add your fragment UI code here
return view;
}
}
```
3. 创建FragmentPagerAdapter类,用于管理ViewPager和Fragment之间的关系,例如:
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] tabTitles = new String[]{"Tab1", "Tab2"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MyFragment();
case 1:
return new MyFragment();
default:
return null;
}
}
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
```
4. 在Activity或Fragment中初始化TabLayout和ViewPager,并设置PagerAdapter,例如:
```
TabLayout tabLayout = findViewById(R.id.tab_layout);
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
```
现在你就可以在TabLayout中看到两个选项卡,每个选项卡都加载了相同的Fragment。你可以根据需要修改Fragment的布局和逻辑,以及PagerAdapter的getItem和getPageTitle方法,来实现自己的界面和功能。
阅读全文