Fragments: Remove all fragments in a view - android

The scenario I am faced with, is in my application I have a single pane and dual pane style layout. Rather than individually handle every single navigation operation possible between the screens, for every different style of layout, I am using a function which sets up the layout correctly when given the desired screen.
It is basically a switch statement for each screen in the app, with a nested switch statement in each screen to handle each layout style. This is what I'm talking about in code:
protected void setupScreen() {
switch(currentScreen) {
case SCREEN_ONE:
switch(currentLayout) {
case SINGLE_PANE:
// Perform actions to setup the screen
break;
case DUAL_PANE:
// Perform actions to setup the screen
break;
}
break;
case SCREEN_TWO:
switch(currentLayout) {
case SINGLE_PANE:
// Perform actions to setup the screen
break;
case DUAL_PANE:
// Perform actions to setup the screen
break;
}
break
// ... etc ....
}
}
In the section where I want to perform the actions to setup the screen, this consists of the following basic three operations:
// Create the fragments if necessary
if (screenFragment == null) {
screenFragment = new myFragment();
}
// Remove the existing fragments from the layout views
// HOW???
// Add the fragments for this screen to the view
getSupportFragmentManager().beginTransaction().add(pane1.getId(), myFragment, "myFragment").commit();
As you can see, what I am struggling with is how to do the second step. How do you remove all Fragments from a given View without knowing exactly which ones you are wanting to remove? The closest I have found is FragmentTransaction.replace() which does successfully do this for every case but when it turns out you are replacing a Fragment with the same fragment. In this case, it does not remove all, then add (like the documentation suggests), it just seems to remove. Is this an issue with using the compatibility libraries or is it not the way FragmentTransaction.replace() should be used?
In any case, how should I go about doing this? Do I have to code a removeAllFragments() function to go through every fragment and detach it or is there a way to do the first half of what the 'two in one' FragmentTransaction.replace() function claims to do?

None of the other answers were really working for me. Here's what I did:
List<Fragment> al = getSupportFragmentManager().getFragments();
if (al == null) {
// code that handles no existing fragments
return;
}
for (Fragment frag : al)
{
// To save any of the fragments, add this check.
// A tag can be added as a third parameter to the fragment when you commit it
if (frag == null || frag.getTag().equals("<tag-name>")) {
continue;
}
getSupportFragmentManager().beginTransaction().remove(frag).commit();
}
or, if you're forced to use it (but not recommended):
.commitAllowingStateLoss();
Also, if you're removing all fragments from the view multiple times, you might consider checking if the current frag is null or isDetached() or isRemoving() or you might get NullPointerExceptions.
Update: The documentation for getSupportFragmentManger().getFragments() is apparently hidden now, but still works just fine in my code. Here's the screenshot of the documentation:
Having said that, since it is hidden, they no longer want this method used, so see my update below.
Update 8-4-15: If you're not using the support library for fragments, there is unfortunately no getFragments() available, but there are still a couple, more inconvenient, options.
Give each fragment a tag or id upon creation, and iterate through them to process each fragment as desired.
Create a listener using onAttachListener so each time a new fragment is attached to the activity, you can store that fragment, and then iterate through that data structure to process each fragment as desired.
When not using the getSupportFragmentManager(), to process a transaction you will need to use getFragmentManager() instead.

The typical mechanism is to use FragmentManager.findFragmentByTag() . You use this and add tags to your fragments (or the alternative for id's). This way you can determine what fragments are currently being managed. Then, once you have a handle to a present fragment (findFragmentByTag returns non-null), you can use FragmentManager.beginTransaction() to start a FragmentTransaction and remove / add the necessary fragments. Working in this way will allow you to avoid the 're-adding' process for the fragment you want to keep.
What I'd probably do is have code like so: (warning psuedo code)
Fragment pane1 = FragmentManager.findFragmentByTag("myFragmentPane1");
Fragment pane2 = FragmentManager.findFragmentByTag("myFragmentPane2");
setupScreen(pane1, pane2);
You should also consider sub-classes of your class instead of having 'everything in one class'. You have a fairly obvious case of Martin Fowler's Replace Conditional with Subclass. Otherwise, I fear this is going to be incredibly hard to manager when you add another screen.

If you use android.support.v4.app.Fragment you can do this:
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}

Turns out FragmentTransaction.replace() is the correct operation and should work correctly. It only does not work when using ActionBarSherlock and SherlockFragmentActivity so I can only assume it is a bug in this compatibility library.
I have confirmed this through using the code below to implement the desired behaviour through Android on API11+, the android compatibility library, and ActionBarSherlock. It only breaks in the last instance.
package com.test.test;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends SherlockFragmentActivity {
// Consistent fragment instance
myFragment myFrag = null;
// Views
FrameLayout fl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
Button b = new Button(this);
b.setText("Repeat");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Reattach the same fragment
getSupportFragmentManager().beginTransaction().replace(fl.getId(), myFrag).commit();
}
});
fl = new FrameLayout(this);
fl.setId(200);
fl.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
myFrag = new myFragment();
getSupportFragmentManager().beginTransaction().add(fl.getId(), myFrag).commit();
ll.addView(b);
ll.addView(fl);
setContentView(ll);
}
public static class myFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView tv = new TextView(getActivity());
tv.setText("My fragment");
tv.setGravity(Gravity.CENTER);
tv.setBackgroundColor(Color.RED);
return tv;
}
}
}

This is more or less how I have handled this. Have all your fragments implement an interface something like:
public interface NamedFragment{
public FragmentName getFragmentName();
}
Make an enum corresponding to your fragments:
public enum FragmentName{
SOME_FRAGMENT,
SOME_OTHER_FRAGMENT;
}
Then in your fragment switching activity:
// Get the manager and transaction separately so you can use both:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
// Get a reference to the fragment(s) currently in the container(s)
Fragment currentFragment = fragmentManager.findFragmentById(position);
FragmentName cFragmentName =
((NamedFragment) currentFragment).getFragmentName();
Fragment nextFragment =
Fragment.instantiate(this, some_new_fragment_string);
FragmentName nFragmentName =
((NamedFragment) nextFragment).getFragmentName();
// Compare the "names"
if(cFragmentName != nFragmentName){
ft.replace(position, nextFragment);
}
You'll have to change things around a little to fit your particulars.

Related

Why do we check for overlapping fragments in OnCreate? (from the documentation)

In the documentation, we have to check if we restore an activity, in order to avoid "overlapping fragments" : why?
Either the activity is destroyed and the fragment is destroyed, so we have to recreate both of them. Or the fragment is retained so that it keeps some data. But in this code, we check if we restore the activity, and if we do, we return the function to avoid "overlapping fragments" :
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;//**HERE**
}
// Create a new Fragment to be placed in the activity layout
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}
Activity stores information about added fragments in its fragment manager. This information persists after configuration changes. Also fragment can save their state, if you want. You can read about retained fragment, which will not be recreated after configuration changes.
Suggestion:
You used fragment manager to add your fragment to activity. After activity recreation the fragment is still tied to the recreated activity.
You added your fragment via add method, and if onCreate method will be called again (for example after rotation), you will add another fragment to your activity.
To avoid it you can use replace instead of add, but in this case replaced fragment will lose your data (which you saved in savedinstancestate for your fragment, so after rotation fragment's savedInstanceState will be null).
So better to add fragment this way:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
if (savedInstanceState == null) {
HeadlinesFragment firstFragment = new HeadlinesFragment()
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container,firstFragment).commit();
}
}
}
Understanding activity and fragment lifecycle is very important. I recommend to read related topics on android developers website or from other sources.
http://developer.android.com/training/basics/activity-lifecycle/index.html
https://www.youtube.com/watch?v=-zr5QLH4Qy4

Trying to add a fragment inside an adapter

I tried to add a fragment on button click action inside an adapter which extends a BaseAdapter.
But to use fragments the class has to extend Fragment to use the FragmentManager.
I've imported :
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
But still facing an error here:
FragmentManager fragmentManager=getFragmentManager();
I've also tried to give the activity reference when getting the FragmentManager,it gave more errors.
Any help would be much appreciated.
Thanks in advance.
Here is my adapter code:
Drawer item(view) onclick action:
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position == 1)// Home
{
Home2Fragment fragment = new Home2Fragment();
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.add(fragment, null);
fragmentTransaction.commit();
}
}
});
Because importing Fragments from support library so, use getSupportFragmentManager method to get FragmentManager :
FragmentManager fragmentManager=<Activity_Context>.getSupportFragmentManager();
Need to use FragmentActivity context to access FragmentManager and also make sure extending FragmentActivity instead of Activity.
It is considered good practice to use let Adapters be an inner class of the List that uses them. That gives the adapter full access to the class using them and if it's a fragment, you can use the fragment manager.

cannot resolve symbol fragmentcontainer

So I've decide to go back into android developing after dropping it for a bit. I Restarted making an old project in android studio I ran into a issue where I'm getting "cannot resolve symbol fragmentcontainer" and I'm sure it was working last time.
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add fragment to the activity
FragmentManager fm = getSupportFragmentManager();
// give fragment to manage
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new HomeFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
It looks like your Activity layout R.layout.activity_main does not contain a view with id fragmentContainer. If that's not the issue, check this related question: Android Studio cannot resolve symbol but code executes correctly.
just using "fragment_container" not "android.R.id.fragment_container" works for me...here is the detail
getFragmentManager().beginTransaction()
.replace(fragment_container, new SettingsFragment())
.commit();
I think you can use
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitNow(); instead of using R.id.fragmentContainer to create fragment in an activity.

can I rely on savedInstanceState != null for adding fragment to layout

android developer tutorial (code beloew) only adds fragment to layout when savedInstanceState != null.
That indicates when savedInstanceState == null fragment is always not added to layout, and when savedInstanceState != null fragment is always added to layout.
Why can I rely on it? I can not find a direct relationship with savedInstanceState and if a fragment is added to layout or not.
the code I am talking about:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
// *** question: I don't understand the comment above. (described in my question)
if (savedInstanceState != null) {
return;
}
HeadlinesFragment firstFragment = new HeadlinesFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}
Fragments are attached to activity automatically. You don't need to add it again if you add it ones. Android will do it by itself.
If savedInstanceState bundle is not null in onCreate then your Activity was recreated(maybe you change orientation or Android killed your application because of low memmory) and you don't need to attach fragment again.
Of course this depend on different situation. There are cases when you need to add different Fragments in onCreate every time Activity change orientation. Then you don't need to use that check.

Get rid of fragments

I decided to not use fragments for now, although Android wants developers to now use it.
But I don't find it useful at the beginning. Unfortunately my IDE prepares everything to use fragments, so my question basically is, how to I get rid of everything, thats necessary for fragments? Is there a way to create a project without fragments? Thats what I did:
package com.pthuermer.juraquiz;
import java.io.IOException;
// import com.pthuermer.juraquiz.QuizActivity.PlaceholderFragment; // only necessary for Fragments
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class AppLaunch extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_launch);
/* FRAGMENTS
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
END FRAGMENTS */
// code goes here...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.app_launch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
* Useredit: not going to use fragments for now.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_launch,
container, false);
return rootView;
}
}
*/
}
I think many people in the Android community will agree that fragments are not easy to handle and even draw new problems, some of them without even a decent proper solution.
Nevertheless, trying to remove all fragments from an app is not an easy task and might require good Android programming skills. You will have to convert your fragments either to views or activities, and that is not so easy to do, especially for activities containing multiple fragments.
The best option so far is to use mortar from Square, but this alternative is not totally ready and mature yet and using it requires, TMHO, advanced Android skills.
So, if I were a relatively new programmer in the Android world, I would keep fragments, get used to them, understand how they can be used to create reusable components and make apps that work on both phones and tablets.
After a while, when you will master them, you will find their drawbacks, and be able to look for alternatives.
I tried to study mortar from Square three times and still I haven't the slightest idea how to use it. So I went ahead and used Kotlin+Anko, switched all Fragments to Views and I'm more than happy - the code base is three times smaller, no dirty Fragment hacks, no NPEs that view has not been created for unknown reason, etc. Just implement views as follows:
class QuestionnaireView(ctx: Context, questions: List<Question>): _LinearLayout {
init {
orientation = LinearLayout.VERTICAL
for (question in questions) {
verticalLayout {
textView {
text = question.title
}.lparams(matchParent, wrapContent)
... etc - generate answer fields as necessary
}.lparams(matchParent, wrapContent)
}
}
}
Advantages:
Pass parameters using constructors like a human being, not via retarded arguments Bundle
No longer worry about the Fragment lifecycle and whether onCreateView() has yet been called or not.
Gets rid of exceptions thrown in Android's moveToState() mammoth method
Get rid of thousands layout.xml files stored in a single directory
Get rid of that styles.xml horrible mess
No need to define multiple layouts just to show a list+details on 720dp devices: just add if(screenWidthDp>=720) { detailView {} } to your init block.
Disadvantages:
No layout previews
Android Studio will become so slow it's almost useless.
You'll need to generate IDs for those views, otherwise their state will be lost on rotate

Categories

Resources