【发布时间】:2022-03-28 13:12:40
【问题描述】:
MainActivity.java 中声明 Viewpager2 的代码:
viewPager = findViewById(R.id.pager);
tabLayout = findViewById(R.id.tabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
pagerAdapter = new ScreenSlidePagerAdapter(MainActivity.this);
viewPager.setAdapter(pagerAdapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
if (position == 0) {
tab.setText("Home");
} else if (position == 1) {
tab.setText("Stats");
} else {
tab.setText("Top");
}
}
}).attach();
viewPager.setCurrentItem(0);
ScreenSlidePagerAdapter 中扩展 FragmentStateAdapter 的代码:
public class ScreenSlidePagerAdapter extends FragmentStateAdapter {
private static final int NUM_PAGES = 3;
public ScreenSlidePagerAdapter(FragmentActivity fa) {
super(fa);
}
@NonNull
@Override
public Fragment createFragment(int position) {
if (position == 0) {
return new MyCoinsFragment();
}else if (position == 1) {
return new StatsFragment();
}else {
return new TopFragment();
}
}
@Override
public int getItemCount() {
return NUM_PAGES;
}
}
我的片段布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/layoutData"
android:layout_marginStart="6dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="10dp"
android:padding="6dp"
android:weightSum="1">
<ImageView
android:layout_width="0dp"
android:layout_height="16dp"
android:layout_gravity="center_vertical"
android:layout_weight="0.1"/>
<TextView
style="@style/subHeadings"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="0.5"
android:singleLine="true"
android:text="sadsda" />
<TextView
style="@style/subHeadings"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="0.4"
android:text="17.2 TH/s"
android:textAlignment="textEnd" />
</LinearLayout>
我需要以编程方式为片段设置标签。将不胜感激一些帮助在哪个方向进入。我知道它将在 Fragment State Adapter 中完成,我需要在其中设置标签,但不确定如何?
【问题讨论】:
标签: java android android-fragments android-viewpager android-viewpager2