I am using a drop-down menu with the different items in the toolbar. In the activity, I am adding the fragment as soon as the menu item is clicked. The fragment OnCreateview gets called and the data is fetched from the API. The logic for the fetching of data remains same for all menu items but only the API endpoint differs. So I am trying to pass the Bundle with API endpoint name and using the same fragment for all the items. But the problem is OnCreateView gets called only first time and the request is made only for first fragment transaction even if I am replacing the same fragment for different item click.
Activity.java
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0: //Clients
Bundle bundle1 = new Bundle();
bundle1.putString("hash-key","item1");
ReportCategoryFragment rp1 = new ReportCategoryFragment();
rp1.setArguments(bundle1);
replaceFragment(rp1,false,R.id.container);
break;
case 1:
Bundle bundle2 = new Bundle();
bundle2.putString("hash-key","item2");
ReportCategoryFragment rp2 = new ReportCategoryFragment();
rp2.setArguments(bundle2);
replaceFragment(rp2,false,R.id.container);
break;
}
}
ReportCategoryFragment
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_runreport, container, false);
setHasOptionsMenu(true);
ButterKnife.bind(this, rootView);
presenter.attachView(this);
reportType = getArguments().getString("hash-key");
Log.v("hashkey",reportType);
presenter.fetchCategories(reportType, false, true);
return rootView;
}
replaceFragment Function
public void replaceFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStateName = fragment.getClass().getName();
boolean fragmentPopped = getSupportFragmentManager().popBackStackImmediate(backStateName,
0);
if (!fragmentPopped && getSupportFragmentManager().findFragmentByTag(backStateName) ==
null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(containerId, fragment, backStateName);
if (addToBackStack) {
transaction.addToBackStack(backStateName);
}
transaction.commit();
}
}
EDIT: FragmentnewInstance method
public static ReportCategoryFragment newInstance() {
ReportCategoryFragment fragment = new ReportCategoryFragment();
Bundle bundle = new Bundle();
fragment.setArguments(bundle);
return fragment;
}