FragmentStatePageAdapter doesn't remove child fragments - android

Having a problem with FragmentStatePagerAdapter and screen change orientation (saving state I guess).
The layout of my app is the following:
Activity -->
Fragment A
Fragment B (contains a FragmentStatePagerAdapter) wich shows 2 fragments
-->
Fragment B1
Fragment B2
All the fragments mentioned inherit from a BaseFragment class that doesn't do anything special but keeping some "global" vars I need.
When Activity starts loads up Fragment A. From a menu I replace Fragment A with Fragment B. Fragment B source is the following:
public class Fragment B extends BaseFragment {
public static String TAG = "b_fragment";
private MyCustomPagerAdapter adapter;
private ArrayList<String> tags = new ArrayList<>();
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new MyCustomPagerAdapter(getFragmentManager());
//adapter = new MyCustomPagerAdapter(getChildFragmentManager());
tags.add(FragmentB1.TAG);
tags.add(FragmentB2.TAG);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sample, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(adapter);
SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout)view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
class MyCustomPagerAdapter extends FragmentStatePagerAdapter {
//class MyCustomPagerAdapter extends FragmentPagerAdapter {
FragmentManager mgr;
public SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public PrepagatePagerAdapter(FragmentManager mgr) {
super(mgr);
this.mgr = mgr;
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentB1();
case 1:
return new FragmentB2();
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
The problem happens when I go to Fragment B then go back again to Fragment A and change orientation: I see while debugging on the onAttach() method of Fragment A that in the FragmentManager Fragment B is no more present (replaced by Fragment A) but Fragment B1 and B2 are there and are called their rispective onAttach() methods, resulting in weird behaviours of the layout. Didn't the child fragments should be remove from the FragmentManager?
At the moment I don't know if more details are needed. I can give further if you need.

Related

How to pass data from a fragment to another fragment that´s inside a view pager?

Description:
I have an activity (Father activity) which has a fragment (Father fragment) inside. This fragment is tabbed and has two fragments (Fragment A and Fragment B) that are changed with view pager.
Father activity sends data to Father fragment which has to take them to Fragment B
Question:
What can I do with Father fragment to take data to Fragment B (which is inside a view pager)?
Extra:
Someone told me I can use interface and I've tried to study it but I couldn't find any good tutorial / explanation.
Hi #Tomas I have Done like this
private class ViewPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment1 = Fragment1.getInstance();
private Fragment fragment2 = Fragmen2.getInstance();
ViewPagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return fragment1;
} else {
return fragment2;
}
}
#Override
public int getCount() {
return 2 ;
}
#Override
public CharSequence getPageTitle(int position) {
return "";
}
Fragment1 getFragment1() {
return (Fragment1) fragment1;
}
Fragment2 getFragment2() {
return (Fragment2) fragment2;
}
}
this is my Fragemnt2 code:
public class Fragment2 extends Fragment {
private TextView text;
public static Fragment2 getInstance() {
return new Fragment2();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragmant_2, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
text = view.findViewById(R.id.text2);
}
public void reloadView(String data){
text.setText(data);
}
}
and from viewpager adapter I call method of faragment 2 like this
adapter.getFragment1().reloadView("data");

Refresh current fragment in tabbed layout viewpager

I am trying to refresh the current fragment in the tabbed layout of my viewpager. I have one fragment (UserProgressFragment) that creates the ViewPager and sets the adapter (UserProgressAdapter) along with creating tabbed layout.
In my UserProgressAdapter, in the getItem() method I am returning two other fragments, (UserWeightTrackerFragment and UserCalorieCounterFragment) based on which tab i am on.
My issue is how do i refresh the fragment and update its content/view from the UserCalorieCounterFragment on a button click, because access to the viewpager and adapter are set in the UserProgressFragment? I have considered notifyDataChange for the adapter but i dont know how to call this from this class as it is set up on the UserProgressFragment class. The purpose of wanting to refresh this page is to update a specific view which is a chart, if context is needed.
I have attached the code below:
UserProgressFragment
public class UserProgressFragment extends Fragment{
public static UserProgressFragment newInstance() {
return new UserProgressFragment();
}
public UserProgressFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_progress, container, false);
ViewPager viewPager = view.findViewById(R.id.progress_viewpager);
viewPager.setAdapter(new UserProgressTabsAdapter(getChildFragmentManager()));
TabLayout tabLayout = view.findViewById(R.id.progress_sliding_tabs);
tabLayout.setupWithViewPager(viewPager, true);
return view;
}
}
UserProgressTabsAdapter
public class UserProgressTabsAdapter extends FragmentStatePagerAdapter {
private static final int PAGE_COUNT = 2;
private String tabTitles[] = new String[]{"Weight Tracker", "Calorie Counter"};
public UserProgressTabsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return UserWeightTrackerFragment.newInstance(position);
case 1:
return UserCalorieCounterFragment.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
UserCalorieCounterFragment (need to refresh this one)
public class UserCalorieCounterFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
public static final String ARG_PAGE = "ARG_PAGE";
public static UserCalorieCounterFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
UserCalorieCounterFragment fragment = new UserCalorieCounterFragment();
fragment.setArguments(args);
return fragment;
}
public UserCalorieCounterFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_calorie_counter, container, false);
Button mAddCalories = view.findViewById(R.id.btn_add_calorie);
mAddCalories.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_add_calorie:
//REFRESH/UPDATE HERE
break;
}
}
You can create a public method in your fragment which contains the view pager which will contain the notifyDataSetChanged() function. And in the view pager fragment/item, you can call getParentFragment() and type cast it to your parent/first fragment and access that public method to notifyDataSetChanged().

Can't swipe to next item inside my detail activity after implementing viewpager

I am trying to swipe item(from listview) in my detail activity using viewpager.
I have 20 items in my listview (data parsed from json) Instead of swiping the next/previous item , It's only the same item that I swipe (20 times).
here is my DetailActivity.
public class DetailsActivity extends FragmentActivity {
Article feed;
int pos;
private DescAdapter adapter;
private ViewPager pager;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_details);
pos = getIntent().getExtras().getInt("pos");
adapter = new DescAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
pager.setCurrentItem(pos);
}
public class DescAdapter extends FragmentStatePagerAdapter {
public DescAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 20;
}
public Fragment getItem(int position) {
return DetailFragment.newInstance(position);
}
}
And my detailFragment
public class DetailFragment extends Fragment {
static DetailFragment newInstance(int position) {
DetailFragment f = new DetailFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
String displaytitle= getActivity().getIntent().getStringExtra("title");
TextView titleF = (TextView)view.findViewById(R.id.title);
titleF.setText(displaytitle);
...
return view;
}
What am I doing wrong?
You are not using the correct argument:
You send the argument "pos2" but you retrieve the argument "title".
#Override
public Fragment getItem(int position) {
DetailFragment frag = new DetailFragment();
Bundle bundle = new Bundle();
bundle.putInt("fPos",position);
frag.setArguments(bundle);
return frag;
}

Nested Fragments with Fragment Pager Adapter [duplicate]

I have an application that uses ActionBarSherlock and inside the main fragment I have a ViewPager which uses several fragments to display different objects of a list.
Main Fragment:
public class CollectionDemoFragment extends SherlockFragment {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public CollectionDemoFragment() {
setTitle(R.string.title);
setHasOptionsMenu(true);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.demo_fragment, container, false);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
return view;
}
#Override
public void onPause() {
//This runs when the fragment goes to backstack
super.onPause();
}
#Override
public void onResume() {
//This runs when the fragment returns from backstack
super.onResume();
}
}
ViewPagerAdapter:
public class DemoCollectionPagerAdapter extends
FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Inside each of this fragments I can create a new Main fragment with a new list to display in the ViewPager and replace the content with this new fragment.
ViewPager Fragments:
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
//Setup components
return rootView;
}
#Override
public void setMenuVisibility(final boolean visible) {
if (visible) {
//Do something
}
super.setMenuVisibility(visible);
}
#Override
public void onPause() {
//This should run when the fragment goes to backstack
super.onPause();
}
#Override
public void onResume() {
//This should run when the fragment returns from backstack
super.onResume();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.someComponent:
Fragment newContent = new CollectionDemoFragment();
switchContent(newContent, true);
break;
}
}
public void switchContent(Fragment newContent, boolean addToBackStack) {
if (newContent != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
ft.replace(R.id.content_frame, newContent);
if (addToBackStack) {
ft.addToBackStack("" + newContent.getId());
}
ft.commit();
}
}
}
This works ok, until I press back and the previous main fragment returns from the backstack.
The screen is empty (since onCreateView is not called the layout is not inflated), the lifecycle methods from the fragments in the ViewPager are never called either when the main fragment enters the backstack, nor when it returns .
The only method called in the fragments of the ViewPager is the setMenuVisibility() so, only the code in there runs.
Anyone knows a way to fix this and why this happens?
Not sure if it matters but I have to support since android 2.3.
When you are creating the view adapter You have to pass the fragment child manager as argument - getChildFragmentManager() instead of getFragmentManager().
Instead of,
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getFragmentManager());
you should use,
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getChildFragmentManager());

ActionBarSherlock with ViewPager not calling ViewPager fragments lifecycle methods when going to and returning from backstack

I have an application that uses ActionBarSherlock and inside the main fragment I have a ViewPager which uses several fragments to display different objects of a list.
Main Fragment:
public class CollectionDemoFragment extends SherlockFragment {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public CollectionDemoFragment() {
setTitle(R.string.title);
setHasOptionsMenu(true);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.demo_fragment, container, false);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
return view;
}
#Override
public void onPause() {
//This runs when the fragment goes to backstack
super.onPause();
}
#Override
public void onResume() {
//This runs when the fragment returns from backstack
super.onResume();
}
}
ViewPagerAdapter:
public class DemoCollectionPagerAdapter extends
FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Inside each of this fragments I can create a new Main fragment with a new list to display in the ViewPager and replace the content with this new fragment.
ViewPager Fragments:
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
//Setup components
return rootView;
}
#Override
public void setMenuVisibility(final boolean visible) {
if (visible) {
//Do something
}
super.setMenuVisibility(visible);
}
#Override
public void onPause() {
//This should run when the fragment goes to backstack
super.onPause();
}
#Override
public void onResume() {
//This should run when the fragment returns from backstack
super.onResume();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.someComponent:
Fragment newContent = new CollectionDemoFragment();
switchContent(newContent, true);
break;
}
}
public void switchContent(Fragment newContent, boolean addToBackStack) {
if (newContent != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
ft.replace(R.id.content_frame, newContent);
if (addToBackStack) {
ft.addToBackStack("" + newContent.getId());
}
ft.commit();
}
}
}
This works ok, until I press back and the previous main fragment returns from the backstack.
The screen is empty (since onCreateView is not called the layout is not inflated), the lifecycle methods from the fragments in the ViewPager are never called either when the main fragment enters the backstack, nor when it returns .
The only method called in the fragments of the ViewPager is the setMenuVisibility() so, only the code in there runs.
Anyone knows a way to fix this and why this happens?
Not sure if it matters but I have to support since android 2.3.
When you are creating the view adapter You have to pass the fragment child manager as argument - getChildFragmentManager() instead of getFragmentManager().
Instead of,
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getFragmentManager());
you should use,
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getChildFragmentManager());

Categories

Resources