I am using an androidx navigation drawer with (fragments), HomeFragment consists of a RecyclerView to show images.
I am trying to call the getMenu() method which updates those images from the MainActivity, but it doesn't work
I have tried to use this MainActivity,but it doesn't work
HomeFragment fragment=new HomeFragment();
fragment.getMenu();
============================HomeFragment================================
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recycler_menu = (RecyclerView)view.findViewById(R.id.recycler_menu);
recycler_menu.setLayoutManager(new GridLayoutManager(context,2));
recycler_menu.setHasFixedSize(true);
mService = Common.getAPI();
getMenu();
return view;
}
public void getMenu() {
compositeDisposable.add(mService.getMenu()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<Category>>() {
#Override
public void accept(List<Category> categories) throws Exception {
displayMenuList(categories);
}
}));
}
private void displayMenuList(List<Category> categories) {
MenuAdapter adapter = new MenuAdapter(context,categories);
recycler_menu.setAdapter(adapter);
}
}
============================MainActivity================================
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu_action_bar ID as a set of Ids because each
// menu_action_bar should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public void onResume() {
super.onResume();
HomeFragment fragment=new HomeFragment();
fragment.getMenu();
}
}
you can't because the method is void and the result is returning back by another method and it's in your fragment.
you should create an interface to pass data from fragment to activity.
HomeFragment:
public class HomeFragment extends Fragment {
private OnAcceptListener listener;
//...
public void getMenu() {
compositeDisposable.add(mService.getMenu()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<Category>>() {
#Override
public void accept(List<Category> categories) throws Exception {
listener.onAccept(categories);
}
}));
}
public void setOnAcceptListener(OnAcceptListener listener) {
this.listener = listener;
}
public interface OnAcceptListener{
void onAccept(List<Category> categories);
}
}
activity:
public class MainActivity extends AppCompatActivity implements HomeFragment.OnAcceptListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
HomeFragment homeFragment = new HomeFragment();
homeFragment.setOnAcceptListener(this);
}
#Override
public void onAccept(List<Category> categories) {
//update here
}
}
Related
i have Activity MainActivity and use some Fragment.
i try the code in google developer and put the code ad in onAttach and onCreate but Interstitial ad show after the the fragment loaded
i worked in the past for ad with activity it's very easy , but it's first time to use ad in fragment class and i search in google search and youtube and no't found any thing help me. so I decided to ask the experts here. I wish you a good day.
public class MainActivity extends AppCompatActivity {
NavController navController ;
NavHostFragment navHostFragment;
AdView adView;
FrameLayout adContainerView;
public static InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
navHostFragment = (NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id.nav_host_fragment);
if (navHostFragment != null) {
navController = navHostFragment.getNavController();
}
NavigationUI.setupWithNavController(bottomNavigationView, navController);
}
The Fragment i want to show ad befor loding and onBackPressed Fragment before back to MainActivity
public class Report_Fragment extends Fragment {
View view;
NavController navController;
DatabaseAccess dp;
int bundle_mor, bundle_even;
int dp_count_mor, dp_count_even;
int total_az;
boolean statusAnimation = false;
Handler handlerAnimation = new Handler(Looper.getMainLooper());
ImageView imgAnimation1, imgAnimation2;
Button button;
public static InterstitialAd mInterstitialAd;
private static final String TAG = "##Report_Fragment##";
public Report_Fragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
//////*******////
//Ads
//Interstitial
MobileAds.initialize(getActivity(), initializationStatus -> {});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(getActivity(),(getResources().getString(R.string.Interstitial_id_Forward)),
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mInterstitialAd = null;
}
});
///////////////**************////////////////
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showAds();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.report_fragment, container, false);
TextView tv_az_count = view.findViewById(R.id.count_athkar);
TextView tv_total_dp = view.findViewById(R.id.count_total);
button = view.findViewById(R.id.button_text);
imgAnimation1 = view.findViewById(R.id.imgAnimation1);
imgAnimation2 = view.findViewById(R.id.imgAnimation2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getActivity() != null)
showAds();
getActivity().onBackPressed();
}
});
dp = DatabaseAccess.getInstance(getActivity());
dp.open();
Bundle bundle = getArguments();
if (bundle != null) {
bundle_mor = bundle.getInt("bundle_morning");
bundle_even = bundle.getInt("bundle_evening");
}
if (bundle_mor > 0) {
tv_az_count.setText(String.valueOf(bundle_mor));
dp_count_mor = dp.getCount_mor();
total_az = bundle_mor + dp_count_mor;
dp.update_n(new Items(1, total_az));
dp.close();
tv_total_dp.setText(String.valueOf(total_az));
} else if (bundle_even > 0) {
tv_az_count.setText(String.valueOf(bundle_even));
dp_count_even = dp.getCount_ev();
total_az = bundle_even + dp_count_even;
dp.update_even(new Items(1, total_az));
dp.close();
tv_total_dp.setText(String.valueOf(total_az));
}
return view;
}
#Override
public void onDestroy() {
if (getActivity() != null) {
BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);
bottomNavigationView.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Destroy_Fragment", Toast.LENGTH_SHORT).show();
}
super.onDestroy();
}
private void showAds() {
if (mInterstitialAd != null) {
mInterstitialAd.show(getActivity());
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
}
My problem it's that I created a default Bottom Navigation Activity and I want to call a fragment method from MainActivity. The problem is that I 'm not able to take a reference of the fragment.
I tried all type of solution here in stackOverFlow.
a lot of method is deprecated.
//MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
FragmentManager fm = getSupportFragmentManager();
HomeFragment fragment = (HomeFragment) fm.findFragmentById(R.id.navigation_home);
fragment.sayHi();
}
//FRAGMENT
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private FragmentHomeBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textHome;
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
public void sayHi(){
Log.d("hi", "hi");
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
I have been investigating for like 4 hours about this problem, but I didnt get any help.
On summary, I am trying to navigate between fragments in Android Studio, using Navigation View. I want to go from Home Fragment to Services Fragment.
The first Home Fragment always load, but when I click on Services item, the fragment Services load, but the data from Home always keeps on the fragment too.
This is my code:
HOME FRAGMENT CLASS
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private PieChart pieChart;
private UserService userService;
private Calendar calendar;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
pieChart = root.findViewById(R.id.pieChart);
userService = UserRepository.getUserService();
getData();
return root;
}
private void getData(){
calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH)+1;
Log.i("INT MONTH", String.valueOf(month));
userService.getHoursPerService(String.valueOf(UserCache.empleado.getId_emp()),String.valueOf(month)).enqueue(new Callback<List<Servicio>>() {
#Override
public void onResponse(Call<List<Servicio>> call, Response<List<Servicio>> response) {
if(response.body().size() == 0){
pieChart.setNoDataText("Sin horas actuales.");
pieChart.setNoDataTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.invalidate();
}else{
List<Servicio> list = response.body();
List<PieEntry> pieEntries = new ArrayList<>();
for(int cont=0;cont<list.size();cont++){
pieEntries.add(new PieEntry(list.get(cont).getTotalHoras(), list.get(cont).getLugarServicio()));
}
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String actual_month = sdf.format(calendar.getTime());
PieDataSet dataSet = new PieDataSet(pieEntries, getResources().getString(R.string.txt_hours_of)+" "+actual_month);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.getDescription().setEnabled(true);
pieChart.getDescription().setText(getResources().getString(R.string.txt_hours_of)+" "+actual_month+".");
pieChart.getDescription().setTextSize(12f);
pieChart.getDescription().setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.99f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleRadius(61f);
pieChart.animateY(2000, Easing.EaseInOutCubic);
pieChart.setEntryLabelColor(ContextCompat.getColor(getContext(),R.color.colorPrimaryDark));
pieChart.setData(data);
pieChart.invalidate();
}
}
#Override
public void onFailure(Call<List<Servicio>> call, Throwable t) {
}
});
}
}
SERVICES FRAGMENT CLASS
public class ServicesFragment extends Fragment {
private ServicesViewModel servicesViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
servicesViewModel = ViewModelProviders.of(this).get(ServicesViewModel.class);
View root = inflater.inflate(R.layout.fragment_myservices, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
servicesViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
MAIN ACTIVITY
public class MainActivityView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private TextView userNameNav;
private TextView userEmailNav;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_view);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_myservices, R.id.nav_startservice)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(this);
userNameNav = headerView.findViewById(R.id.userNameNav);
userEmailNav = headerView.findViewById(R.id.userEmailNav);
userNameNav.setText(UserCache.empleado.getNombre()+" "+UserCache.empleado.getApellidos());
userEmailNav.setText(UserCache.empleado.getEmail());
navigationView.bringToFront();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_view, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
AlertDialog.Builder alerta = new AlertDialog.Builder(this);
alerta.setTitle(getResources().getString(R.string.txt_dialog_exit_app));
alerta.setPositiveButton(getResources().getString(R.string.txt_yes_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alerta.setNegativeButton(getResources().getString(R.string.txt_no_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alerta.show();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_home:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,new HomeFragment()).commit();
case R.id.nav_myservices:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new ServicesFragment()).commit();
//NavHostFragment.findNavController(new ServicesFragment());
break;
case R.id.nav_startservice:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new StartServiceFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
onNavigationItemSelected is where I do the navigation.
I tried everything, changing the ConstraintLayout to Relative, insert the fragments from xml into framelayout...
Also, I am using MVVM.
If more information is needed i can post here then.
PD: Sorry if I posting something wrong, this is my first time here.
SOLUTION: I forgot completly to break the first case onNavigationItemSelected.
Not able to pass the retrived list of data from retrofit to a recyclerview in fragment!
Tried some solutions but not working!
I have tried creating methods in fragment and passing but not working!
Getting null!
Activity
TabLayout tabLayout;
ViewPager viewPager;
RecyclerView recyclerView;
//vars
private Dto dto;
List<Post_DTO> post_dto_list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
dto=new Dto();
UpdateList();
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Dashboard"));
tabLayout.addTab(tabLayout.newTab().setText("Converations"));
tabLayout.addTab(tabLayout.newTab().setText("Profile"));
PostFragment pf=new PostFragment();
pf.passData(getApplicationContext(),post_dto_list);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//ft.add(R.id.posts_recyclerview, ft);
ft.addToBackStack(null);
ft.commit();
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println(tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void UpdateList() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.postUrl))
.addConverterFactory(GsonConverterFactory.create())
.build();
PostsInterface postsInterface =retrofit.create(PostsInterface.class);
Call<Post_DTO_Resp> call= postsInterface.getPosts();
call.enqueue(new Callback<Post_DTO_Resp>() {
#Override
public void onResponse(Call<Post_DTO_Resp> call, Response<Post_DTO_Resp> response) {
//pDialog.dismiss();
if(!response.isSuccessful())
{
Toast.makeText(getApplicationContext(),"Loading the posts!",Toast.LENGTH_SHORT).show();
}
Post_DTO_Resp posts = response.body();
post_dto_list=posts.getPost_dto_list();
//dto.setList(post_dto_list);
}
#Override
public void onFailure(Call<Post_DTO_Resp> call, Throwable t) {
//pDialog.dismiss();
if(t.getMessage().equals("End of input at line 1 column 1 path $"))
{
Toast.makeText(getApplicationContext(), "There are no posts!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Api Error!", Toast.LENGTH_LONG).show();
}
}
});
}
}
Fragment!
public class PostFragment extends Fragment {
RecyclerView recyclerView;
View v;
Dto dtobject;
private static final String DESCRIBABLE_KEY = "list";
private Describable mDescribable;
List<Post_DTO> post_dto_list;
public PostFragment() {
// Required empty public constructor
}
public void passData(Context context, List<Post_DTO> list) {
//mContext = context;
post_dto_list = list;
// mIndex = pos;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_posts, container, false);
recyclerView=(RecyclerView) v.findViewById(R.id.posts_recyclerview);
RecyclerViewAdapter recyclerViewAdapter=new RecyclerViewAdapter(getContext(),post_dto_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
//listupdater();
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Just want to get the post_dto_list from Activity to fragment class!
Suggestions please!
You can use a bundle to pass a list from activity to fragment.
In activity:
Bundle bundle = new Bundle();
bundle.putSerializable("list", mList);
mFragment.setArguments(bundle);
And then in your fragment:
mList = getIntent().getExtras().getSerializable("list"));
But the POJO that your list contains should be parcelable ( Parcelable better than Serializable).
Your POJO should be something like:
public class MyPOJO implements Parcelable {
For more info refer this.
After migrating my navigation to the new Jetpack Navigation Component, I found that after navigating back and forth using the the libraries, the content/layout of the first two fragments in my ViewPager disappears. After clicking through the tabs, it comes back though.
At first I thought it was because of the errors that I saw in the logcat, but after fixing them, the problem was still there.
Here is the code of my MainActivity:
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindResources();
// Setup Toolbar & Navigation Component
setSupportActionBar(toolbar);
setupNavigation();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_options, menu);
return super.onCreateOptionsMenu(menu);
}
private void setupNavigation() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph())
.setDrawerLayout(drawerLayout)
.build();
NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
Here is the code of my ViewPagerAdapter:
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
public void addFragment(#NonNull Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
This is my HomeFragment:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindResources(view);
// ViewPager
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPagerAdapter.addFragment(new TodayFragment(), getString(R.string.tab_today_title));
viewPagerAdapter.addFragment(new PriorityFragment(), getString(R.string.tab_priority_title));
viewPagerAdapter.addFragment(new PlannedFragment(), getString(R.string.tab_planned_title));
viewPagerAdapter.addFragment(new TasksFragment(), getString(R.string.tab_tasks_title));
viewPager.setAdapter(viewPagerAdapter);
// TabLayout
tabLayout.setupWithViewPager(viewPager);
}
Java: I fixed the problem by replacing
= new ViewPagerAdapter(getActivity().getSupportFragmentManager());
with
= new ViewPagerAdapter(getChildFragmentManager());
Kotlin: By replacing
= ViewPagerAdapter(fragmentManager)
with
= ViewPagerAdapter(childFragmentManager)