I only know how to add fragment and remove.
also show and hide.
I just want to initialize fragment.
onCreate {
getFragmentManager().beginTransaction().add(R.id.top_container, new AuthProgressDialog(), AuthProgressDialog.class.getSimpleName()).commit();
getFragmentManager().beginTransaction().hide( getFragmentManager().findFragmentByTag(AuthProgressDialog.class.getSimpleName()) ).commit();
}
This is bad code, isn't it?
If you have any idea, please let me know.
Thanks.
This is sample method which you can define inside your FragmentActivity and call from any of the fragment. in which if you want to allowing adding to backstack than just remove comment line from transaction.addToBackStack("back"); and check popup backstack as per your requirement inside FragmentActivity.
public void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FormFragment();
break;
case 1:
fragment = new HomeFragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager
.beginTransaction();
if (position != 0)
// transaction.addToBackStack("back");
transaction.replace(R.id.main_ll_container, fragment).commit();
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
Use this code :
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fraggy = new DummyFragment();
fragmentTransaction.add(R.id.fragment_container, fraggy);
fragmentTransaction.commit();
Related
I would like to see if a view exists before loading a fragment. In my method that loads the fragment i have below :
public void loadFragment(Fragment fragment){
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Replace the layout holder with the required Fragment object.
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment);
// Commit the Fragment replace action.
fragmentTransaction.commit();
}
What i want is to check if R.id.outbound_dashboard_hourly_queued exists before loading
How do i proceed ?
just do findViewById(R.id.outbound_dashboard_hourly_queued) and then load the fragment if the view is not Null keep a if check.
public void loadFragment(Fragment fragment){
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Replace the layout holder with the required Fragment object.
View yourView= findViewById(R.id.outbound_dashboard_hourly_queued);
if(yourView!=null){
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment);
// Commit the Fragment replace action.
fragmentTransaction.commit();
}
}
try this
Check is Fragmnet added or not
if (getCurrentFragment() instanceof YourFragment)
Add Framgnet
replaceFragment(new HomeFragment(), "YourFragment");
Methods
private void replaceFragment(Fragment fragment, String tag)
{
Fragment currentFragment = getCurrentFragment();
if (currentFragment != null)
getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
getSupportFragmentManager().beginTransaction().add(R.id.container_main, fragment, tag).commit();
}
public Fragment getCurrentFragment()
{
FragmentManager manager = getSupportFragmentManager();
return manager.findFragmentById(R.id.container_main);
}
private void popBackStack()
{
FragmentManager fragmentManager = getSupportFragmentManager();
int total = fragmentManager.getBackStackEntryCount();
for (int i = 0; i < total; i++)
{
fragmentManager.popBackStack();
}
}
You can use findFragmentByTag(String tag) method provided by FragmentManager to check if the fragment already exists or not.
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG);
For this to work, you need to commit your fragment with that TAG using -
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment, TAG);
please follow the count checking before replace if the count == 0 add else replace your code must be like
public void loadFragment(Fragment fragment){
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
// Begin Fragment transaction.
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Replace the layout holder with the required Fragment object.
if(fragmentManager.getFragments().size() == 0){
fragmentTransaction.add(R.id.outbound_dashboard_hourly_queued, fragment).commit();
}else {
fragmentTransaction.replace(R.id.outbound_dashboard_hourly_queued, fragment).commit();
}
// Commit the Fragment replace action.
}
please try with this and let me know.
I am trying to talk to the fragments from activity.
Here in my MainActivity I am adding multiple fragments ok so for fine.
My main requirement is I don't want to add if fragment is already added.
So how can we check this condition?
Please help me some one.
code:-
private void intializingFragments(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private View.OnClickListener intialization() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
int getId = v.getId();
if (getId == R.id.first) {
intializingFragments(new Fragment1());
} else if (getId == R.id.second) {
intializingFragments(new Fragment2());
} else if (getId == R.id.third) {
intializingFragments(new Fragment3());
}
}
};
}
You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.
Fragment fragmentA = fragmentManager.findFragmentByTag("frag1");
if (fragmentA == null) {
// not exist
} else {
// fragment exist
}
for example:- http://wiki.workassis.com/android-load-two-fragments-in-one-framelayout/
You may find fragment in fragmentmanager:
List<Fragment> frags = getSupportFragmentManager().getFragments();
for (Fragment f : frags) {
<find what you want>...
}
Or you may add fragment with tag:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frame, new MyFragment(), "frag1")
.commit();
And find by tag
getSupportFragmentManager().findFragmentByTag("frag1");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment topFragment = fragmentManager.findFragmentById(R.id.container);
FragmentA fragmentA = new FragmentA();
if(topFragment!= null)
{
transaction.remove(topFragment);
transaction.add(R.id.container, fragmentA, "FA");
transaction.commit();
}
else
{
transaction.add(R.id.container, fragmentA, "FA");
transaction.commit();
}
try this
private void intializingFragments(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment topFragment = fragmentManager.findFragmentById(R.id.container);
if(topFragment!= null)
{
fragmentTransaction.remove(topFragment);
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else
{
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
How to check whether a fragment exists, without knowing its resource ID or tag:
// MyActivity.kt
val exists: Boolean = supportFragmentManager
.fragments
.filterIsInstance<MyFragment>()
.isNotEmpty()
There are many ways by which you can track the last added fragment. The simplest one is by finding the tag within fragment manager. Here is the sample code of it:
public boolean isFragmentPresent(String tag) {
Fragment frag = getSupportFragmentManager().findFragmentByTag(tag);
if (frag instanceof HomeFragment) {
return true;
} else
return false;
}
Alternatively, you can use your own variable to check whether the last added fragment is the same as the current fragment. Here is the sample code for it:
public boolean isCurrentFragment(Fragment fragment) {
if (fragment instanceof HomeFragment && getLastAddedFragment() instanceof HomeFragment) { // getLastAddedFragment() is a method which return the last added fragment instance
return true;
} else
return false;
}
And you can use it like:
if (isCurrentFragment(new HomeFragment())) {
// Last added Fragment is the HomeFragment
}
You can go for popBackStack Pop the last fragment transition from the manager's fragment back stack. If there is nothing to pop, false is returned. enter link description here
You can get the list of previously added fragments from the fragment manager. Then just check whether the list contains your fragment object or not.
getSupportFragmentManager().getFragments().contains(yourFragment);
This one doesn't work
!getSupportFragmentManager().getFragments().contains(fragment)
This works for me
getSupportFragmentManager().findFragmentByTag(fragment::class.java.getSimpleName()) == null
I am new to android working first time on fragment.I am creating an app in which I want to add a fragment on frame layout.I am able to do this but now what I want is to remove the same fragment which i added by that same button click I tried but couldn't. here is my code.
public void onClick(View v) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
if(v.getId() == R.id.clickme){
if(getSupportFragmentManager().findFragmentById(R.layout.fragment_one) != null){
// getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.layout.fragment_one)).commit();
Fragment fragment = new FragmenOne();
fragmentManager.beginTransaction().remove(fragment).commit();
}else{
Fragment fragment = new FragmenOne();
// android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.my_frame, fragment)
.commit();
}
}
}
You need to do in this manner
Fragment f = fragmentManager.findFragmentById(R.id.my_frame);
if(f instanceof FragmenOne) {
FragmenOne oneFragment = (FragmenOne) f;
FragmentTransaction trans = manager.beginTransaction();
trans.remove(oneFragment);
trans.commit();
fragmentManager.popBackStack();
}else{
Fragment fragment = new FragmenOne();
fragmentManager.beginTransaction()
.replace(R.id.my_frame, fragment)
.commit();
}
I have something like this inside my activity:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position+1) {
case 1: {
fragment = new Fragment_Login();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment)
.commit();
break;
}
case 2: {
SwipeRefreshListFragment swipeFragment = new Fragment_List_Of_Assessments();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, swipeFragment)
.commit();
break;
}
case 3: {
fragment = new Fragment_Report();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment)
.commit();
break;
}
case 4: {
fragment = new Fragment_Settings();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment)
.commit();
break;
}
default:
break;
}
}
The program automatically loads case1, but when case2 is selected, getSupportFragmentManager loads the Fragment on top of case1. I guess there are some problem with using both supportFragmentManager and FragmentManager. They seem to have their own stack. The problem is that I cannot use only either one of them because the SwipeToRefresh Android example uses ListView which needs support.v4.Fragment which needs the old FragmentManager. So how is it possible to integrate both FragmentManagers together?
I have accomplished something like this when using PreferenceFragment (not supported by support library version). In order to achieve this I kept inside my Activity a pair of boolean (isLastFragmentSupportType and lastFragmentShowed) and also a String (lastFragmentTag).
At the beginning your Activity will have both of them to false. And when you add a new Fragment you use these 2 boolean to know if you need to clean the other FragmentManager or not. I'll use your code as an example:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position+1) {
case 1: {
if(isLastFragmentSupportType && lastFragmentShowed)
{//As your last fragment was a support type you need to clear your supportFragmentManager
android.support.v4.app.Fragment fr_v4 = getSupportFragmentManager().findFragmentByTag(lastFragmentTag);
getSupportFragmentManager().beginTransaction().remove(fr_v4).commit();
}
fragment = new Fragment_Login();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment,TAG1)
.commit();
lastFragmentTag = TAG1;
lastFragmentShowed = true;
isLastFragmentSupportType = false;
break;
}
//And so on with the others
You need to check what type (support or not) of fragment you are going to use, and check these variables to see if the last fragment was of a different type. If that is the case clean the other fragmentmanager to "clear" the screen so they wont overlap.
Also use TAGS to identify and retrieve your current fragments so you do not need to have Fragment variables over your code.
Finally use onSavedInstanceState so as to keep these values in case you need them.
Hope it helps :)
This answer is inspired from answer by zozelfelfo.
Use these two methods to replace fragments instead of getFragmentManager.beginTransaction.replace...
private void replaceFragment(Fragment fragment, String fragmentTag) {
if(lastFragmentShowed && isLastFragmentSupportType) {
android.support.v4.app.Fragment fr_v4 = getSupportFragmentManager().findFragmentByTag(lastFragmentTag);
getSupportFragmentManager().beginTransaction().remove(fr_v4).commit();
}
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentTag)
.commit();
lastFragmentTag = fragmentTag;
lastFragmentShowed = true;
isLastFragmentSupportType = false;
}
private void replaceFragment(android.support.v4.app.Fragment fragment, String fragmentTag) {
if(lastFragmentShowed && !isLastFragmentSupportType) {
Fragment fr = getFragmentManager().findFragmentByTag(lastFragmentTag);
getFragmentManager().beginTransaction().remove(fr).commit();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentTag)
.commit();
lastFragmentTag = fragmentTag;
lastFragmentShowed = true;
isLastFragmentSupportType = true;
}
I'm using BottomNavigationView as Tab Bar and switching fragments as tabs. All but one fragment are Support Fragments (and last one is PreferenceFragment). I'm using "hide-add-show" rather than "remove-replace". So, status of fragments in other tabs can be preserved.
Original function to switch:
private Fragment lastFragment = null;
private void switchFragment(Fragment fragment) {
if (lastFragment != fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (null != lastFragment) {
transaction.hide(lastFragment);
}
lastFragment = fragment;
if (!fragment.isAdded()) {
transaction.add(R.id.fragment_container, fragment);
}
transaction.show(fragment).commitAllowingStateLoss();
}
}
I don't use tag nor boolean, just want to keep a reference to last fragment object. So, when switching, just call switchFragment() with instance of any fragment:
private Object lastFragment = null;
private void switchFragment(Object fragment) {
if (lastFragment != fragment) {
if (null != lastFragment) {
if (lastFragment instanceof android.support.v4.app.Fragment) {
hideFragment((android.support.v4.app.Fragment) lastFragment);
} else if (lastFragment instanceof android.app.Fragment) {
hideFragment((android.app.Fragment) lastFragment);
}
}
lastFragment = fragment;
if (fragment instanceof android.support.v4.app.Fragment) {
showFragment((android.support.v4.app.Fragment) fragment);
} else if (fragment instanceof android.app.Fragment) {
showFragment((android.app.Fragment) fragment);
}
}
}
So, this function still do the same things but switch between Support Fragment and Native Fragment by checking the target class. Helper functions:
// Support Version:
private void hideFragment(android.support.v4.app.Fragment fragment) {
getSupportFragmentManager().beginTransaction().hide(fragment).commit();
}
private void showFragment(android.support.v4.app.Fragment fragment) {
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!fragment.isAdded()) {
transaction.add(R.id.fragment_container, fragment);
}
transaction.show(fragment).commitAllowingStateLoss();
}
// Native Version:
private void hideFragment(android.app.Fragment fragment) {
getFragmentManager().beginTransaction().hide(fragment).commit();
}
private void showFragment(android.app.Fragment fragment) {
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (!fragment.isAdded()) {
transaction.add(R.id.fragment_container, fragment);
}
transaction.show(fragment).commitAllowingStateLoss();
}
To avoid confusion, I removed the import so classes require full names.
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
FragmentA frag = new FragmentA();
ft.replace(android.R.id.content, frag);
}
else
{
FragmentB frag = new FragmentB();
ft.replace(android.R.id.content, frag);
}
}
The above code loads in fragments, the problem is it creates a new instance of each fragment, so going to and from tabs, the fragment reloads. What is the best way to make it so it does not create a new instance of each fragment eahc time and only uses the origial instance?
Thanks
Use an attribute in your class
private frag = new Fragment();
...
if(tab.getPosition()==0)
{
ft.replace(android.R.id.content, frag);
}
You will need to add a method to push a fragement to the backstack or pop items off so we may reuse a fragment already in the back stack. The "name" param in the following function provides the best way to locate and pop back (if needed)
private void popToOrPushFragmentWithName(Fragment fragment, String name, FragmentTransaction ft) {
FragmentManager manager = getSupportFragmentManager();
// Scan the back stack for an entry with the given fragment name
int count = manager.getBackStackEntryCount();
FragmentManager.BackStackEntry entry = null;
while (--count >= 0) {
FragmentManager.BackStackEntry check = manager.getBackStackEntryAt(count);
if (check.getName() != null && check.getName().equals(name)) {
entry = check;
break;
}
}
if (entry == null) {
// There is no entry, so push the fragment
ft.replace(R.id.fragment_container, fragment);
ft.addToBackStack(name);
// might not need this next line (since you are using tabselected override)
ft.commit();
} else {
// Pop back to the existing fragment (0 = not inclusive, so our fragment by index is on top)
manager.popBackStackImmediate(entry.getId(), 0);
}
}
Your onTabselected should look something like this :
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
FragmentA frag = new FragmentA();
popToOrPushFragmentWithName(frag, "FragmentA", ft);
}
else
{
FragmentB frag = new FragmentB();
popToOrPushFragmentWithName(frag, "FragmentB", ft);
}
}
I hope this helps. :)