要将选项卡滑动器ViewPager与选项卡工具栏TabLayout连接在一起,可以按照以下步骤进行操作:
TabLayout tabLayout = findViewById(R.id.tab_layout);
ViewPager viewPager = findViewById(R.id.view_pager);
// 创建一个适配器来管理ViewPager中的片段
FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@NonNull
@Override
public Fragment getItem(int position) {
// 返回对应位置的Fragment
return MyFragment.newInstance(position);
}
@Override
public int getCount() {
// 返回Fragment的数量
return 3;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
// 返回对应位置的选项卡标题
return "Tab " + position;
}
};
// 将适配器设置给ViewPager
viewPager.setAdapter(adapter);
// 将ViewPager与TabLayout连接起来
tabLayout.setupWithViewPager(viewPager);
public class MyFragment extends Fragment {
private static final String ARG_POSITION = "position";
public static MyFragment newInstance(int position) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
TextView textView = rootView.findViewById(R.id.text_view);
if (getArguments() != null) {
int position = getArguments().getInt(ARG_POSITION);
textView.setText("This is tab " + position);
}
return rootView;
}
}
这样,就可以使用TabLayout和ViewPager创建一个具有滑动选项卡的Android应用了。