Fragment activity goes to zero when another fragment is added

I used the android.cupport-v4.jar compatibility library that android gives, I found a problem, I started creating a TabActivity containing several fragments in it.

I have a start tab with a GridView, from the element listener in the adapter I call the following code:

FragmentManager manager = getSupportFragmentManager(); FragmentTransaction ft = manager.beginTransaction(); ft.add(R.id.relativeLayoutContent, newFragment); // ft.replace(R.id.relativeLayoutContent, newFragment); ft.addToBackStack(null); ft.commit(); 

The problem is, when I open a new fragment and return to the first, it is not suitable for onAttach, because it was never attached, and since there was a new fragment, the activity now holds the last, but not the first, if I try to click an element again it will crash, telling me that the getActivity method from the fragment is null.

Any workaround for this?

+4
source share
1 answer

I'm not quite sure what you are trying to accomplish, but I will still be applied to it.

You should use a fragmenter to store different fragments, but when you use the add method in FragmentTransaction, tag your fragments so that you can easily switch between fragments.

TabActivity is also deprecated. Have you thought about using tabs in an ActionBar? http://developer.android.com/guide/topics/ui/actionbar.html#Tabs

Here is a snippet that I pulled out of what I'm currently working on:

 public void changeFragment(String tag){ Fragment tmpFragment; FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); //look to see if we have already added the fragment tmpFragment = getFragmentManager().findFragmentByTag(tag); //we currently have a fragment, hide it if (currentFragment != null){ fragmentTransaction.detach(currentFragment); } //did not find the fragment if (tmpFragment == null){ if (tag.equals("map")){ currentFragment = CustomMapFragment.newInstance(); } else if (tag.equals("list")){ currentFragment = ListFragment.newInstance(); }else { //TODO } //add fragment for 1st time fragmentTransaction.add(R.id.content_frame, currentFragment, tag); } else { //we found the fragment currentFragment = tmpFragment; fragmentTransaction.attach(currentFragment); //show the fragment we found } fragmentTransaction.commit(); } 

You can use these methods to switch between fragments based on their tag.

0
source

Source: https://habr.com/ru/post/1402465/


All Articles