XML:
<?xml version="1.0" encoding="utf-8"?>代码部分:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.tab.TabActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="MissingConstraints">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:id="@+id/tab_menu"
android:layout_height="40dp"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="122dp"
tools:ignore="MissingConstraints">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tab_viewpager"
tools:ignore="MissingConstraints" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment[] list={new BpmFragment(),new BpmFragment(),new BpmFragment()};实现效果
TabLayout tl;
String[] title={"热量计算器","消耗计算器","每日打卡"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
ViewPager2 vp2=(ViewPager2)findViewById(R.id.tab_viewpager);
tl=(TabLayout)findViewById(R.id.tab_menu);
for(String s:title)
tl.addTab(tl.newTab().setText(s));
vp2.setAdapter(new FragmentStateAdapter(this) {
@NonNull
@Override
public Fragment createFragment(int position) {
return list[position];
}
@Override
public int getItemCount() {
return list.length;
}
});
new TabLayoutMediator(tl, vp2, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int i) {
tab.setText(title[i]);
}
}).attach();
}
//选中状态时
void switchFragment(int index) {
if (!Objects.requireNonNull(tl.getTabAt(index)).isSelected()) {
Objects.requireNonNull(tl.getTabAt(index)).select();
}
}
- 本文标题: tablayout与ViewPager2之间如何运用
- 文章分类:【Android】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.