I want to add or remove a fragment from the tab based on switch position
if switch is on then the fragment will be added if switch is off then the tab will be removed
here is the code i did in the main activity this actually works but only when the app is retstared and get the details from the Sharred Prefrence
MainActivity.java
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
mSharedPrefs_nsfw_settings = getSharedPreferences(SHARED_PREFS_NAME_NSFW, Context.MODE_PRIVATE);
boolean rewardGranted = mSharedPrefs_nsfw_settings.getBoolean(REWARD_GRANTED_KEY, false);
viewPagerAdapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), getLifecycle(), rewardGranted);
viewPager.setAdapter(viewPagerAdapter);
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
// Set the tab titles using switch-case
switch (position) {
case 0:
tab.setText("Meme");
break;
case 1:
tab.setText("Art");
break;
case 2:
if (rewardGranted) {
tab.setText("NSFW");
} else {
tab.setText("Settings");
}
break;
case 3:
tab.setText("Settings");
break;
}
}).attach();
FragmentStateAdapter
public FragmentViewPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,boolean rewardGranted) {
super(fragmentManager, lifecycle);
fragmentList.add(new MemeFragment());
fragmentList.add(new ArtFragment());
if (rewardGranted) {
fragmentList.add(new NsfwFragment());
}
fragmentList.add(new SettingsFragment());
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
/**
* Return the number of views available.
*/
@Override
public int getItemCount() {
return fragmentList.size();
}
public Fragment getFragment(int position) {
// Retrieve the fragment at the specified position
return fragmentList.get(position);
}
and here is the Switch code which currently just adding the sharedprefrence
SettingsFragment.java
nsfwSetting.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = mSharedPrefs_nsfw_settings.edit();
editor.putBoolean(REWARD_GRANTED_KEY, isChecked);
editor.apply();
}
});
nsfwSetting.setChecked(mSharedPrefs_nsfw_settings.getBoolean(REWARD_GRANTED_KEY, false));