android-fragments TabLayout标签在切换标签时被破坏

6yoyoihd  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(164)

我在我的活动中使用了标签页布局,它有两个标签页。当我切换到另一个标签页时,当前标签页片段被破坏,另一个标签页从头开始创建(从Oncreate()生命周期方法),我以前曾经这样做过。

private void Tablayout_TabSelected(object sender, TabSelectedEventArgs e)
    {
        Tab tab = e.Tab;
        if (tab.Position == 0)
        {
            SupportFragmentManager.BeginTransaction().Replace(Resource.Id.fragmentContainerView, listFrag ??= new MusicListFragment(), "ListFrag").Commit();
        }
        else if (tab.Position == 1)
        {
            SupportFragmentManager.BeginTransaction().Replace(Resource.Id.fragmentContainerView, favFrag ??= new FavoriteSongsFragment(), "FavFrag").Commit();
        }
    }

将整个片段保存在内存中而不是每次都创建一个新片段,这难道不是一个好主意吗?
或者我如何改进我的切换?

sxpgvts3

sxpgvts31#

"试试这个"
使用FragmentPagerAdapter是一种简单且工作良好的方法
1.创建class扩展FragmentPagerAdapter
1.在您的适配器中遵循以下代码

public class FragmentAdapter extends FragmentPagerAdapter {
    Context context;
    int totalTaps;

  public FragmentAdapter(@NonNull FragmentManager fm, Context context, int totalTaps) {
    super(fm);
    this.context = context;
    this.totalTaps = totalTaps;
}

@NonNull
@Override
public Fragment getItem(int position) {

    switch (position){
        case 0:
            MusicListFragment musicListFragment= new MusicListFragment();
            return musicListFragment;
        case 1:
            FavoriteSongsFragment favoriteSongsFragment= new FavoriteSongsFragment();
            return favoriteSongsFragment;

        default:
            return null;
    }
}

 @Override
 public int getCount() {
    return totalTaps;
  }
}

主要活动

public class HomePage extends AppCompatActivity {

ViewPager viewPager;
TabLayout tabLayout;
FragmentAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);
    viewPager = findViewById(R.id.viewPager);
    tabLayout = findViewById(R.id.tabLayout);
    adapter = new FragmentAdapter(getSupportFragmentManager(),getApplicationContext(),2);

    tabLayout.addTab(tabLayout.newTab().setText("ListFrag"));
    tabLayout.addTab(tabLayout.newTab().setText("FavFrag"));

     viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
     tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
         @Override
         public void onTabSelected(TabLayout.Tab tab) {
             viewPager.setCurrentItem(tab.getPosition());
         }

         @Override
         public void onTabUnselected(TabLayout.Tab tab) {

         }

         @Override
         public void onTabReselected(TabLayout.Tab tab) {

         }
     });
     viewPager.setAdapter(adapter);
}

相关问题