Last active
November 30, 2016 14:43
-
-
Save reline/e74f1cff194c7f3e96cd3f696243b067 to your computer and use it in GitHub Desktop.
Android Fragment Manager - SDK 16+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle; | |
import android.support.v4.app.Fragment; | |
import android.support.v4.app.FragmentManager; | |
import android.support.v7.app.AppCompatActivity; | |
import android.util.Log; | |
public class MyActivity extends AppCompactActivity { | |
private static final String FRAGMENT_ONE = "FRAGMENT_ONE"; | |
private static final String FRAGMENT_TWO = "FRAGMENT_TWO"; | |
private String currentFragmentTag; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.layout_myactivity); | |
} | |
/* ... */ | |
if (caseOne) { | |
swapFragment(MyFragmentOne.class, FRAGMENT_ONE); | |
} else if (caseTwo) { | |
swapFragment(MyFragmentTwo.class, FRAGMENT_TWO); | |
} | |
/*...*/ | |
public void swapFragment(Class<? extends Fragment> fragmentClass, String fragmentTag) { | |
try { | |
FragmentManager fragmentManager = getSupportFragmentManager(); | |
Fragment fragment = fragmentManager.findFragmentByTag(fragmentTag); | |
if (fragment == null) { | |
fragmentManager.beginTransaction().add(R.id.fragment_container, fragmentClass.newInstance(), fragmentTag).commit(); | |
} else { | |
fragmentManager.beginTransaction().show(fragment).commit(); | |
} | |
if (currentFragmentTag != null) { | |
Fragment currentFragment = fragmentManager.findFragmentByTag(currentFragmentTag); | |
if (currentFragment != null) { | |
fragmentManager.beginTransaction().hide(currentFragment).commit(); | |
} | |
} | |
currentFragmentTag = fragmentTag; | |
} catch (Exception e) { | |
Log.e(getClass().getSimpleName(), e.getMessage(), e); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<FrameLayout | |
xmlns:android="http://schemas.android.com/apk/res/android" | |
android:id="@+id/fragment_container" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment