How to hide all other fragments - java

Just for coding practice, I'm creating a small game.
Currently I added a optionmenu, and if a item is selected a new fragment is shown. Thanks working good.
My problem is that the game fragment should never be destroyed. Only hidden.
If I'm using my code below both frames (about and help) can exist at the same time. But if I use replace on R.id.container the game fragment will stop (there is a timer in there).
Here is my Java code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(false);
getFragmentManager().popBackStack();
return true;
case R.id.action_about:
if (getFragmentManager().findFragmentByTag("about_fragment") == null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// Gets the game fragement so it can be hidden
Fragment fragment = getFragmentManager().findFragmentByTag("game_fragment");
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.add(R.id.container, new AboutFragment(), "about_fragment")
.hide(fragment)
.addToBackStack("about_fragment")
.commit();
return true;
}
return true;
case R.id.action_help:
if (getFragmentManager().findFragmentByTag("help_fragment") == null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// Gets the game fragement so it can be hidden
Fragment fragment = getFragmentManager().findFragmentByTag("game_fragment");
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.add(R.id.container, new HelpFragment(), "help_fragment")
.hide(fragment)
.addToBackStack("help_fragment")
.commit();
return true;
}
return true;
default:
return super.onOptionsItemSelected(item);
}
Here my XML with the container:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DoNothingGame"
tools:ignore="MergeRootFrame" />
I could ask in every case in the switch if the other fragments are shown and hide them, but I think code will blow up a LOT if I use, for example, 10 or 20 menu items.
So.. Is there a way to hide every fragment except the new one?
Thanks for your help!

Maybe a little bit late but I manage to implement it like this:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
for (Fragment frag : fm.getFragments()){
ft.hide(frag);
}
ft.commit();

Related

how to go back to the previous fragment [duplicate]

This question already has an answer here:
Navigation View Global Action Back State
(1 answer)
Closed 1 year ago.
I have a search button, with an actionViewClass. When this button is clicked a new fragment opens, and I want when the back button is clicked to go back to the previous fragment.
PS: I am using navigation graph
My toolbar_menu.xml
<item
android:id="#+id/search"
android:title="Pesquisar"
android:orderInCategory="103"
android:icon="#drawable/ic_search"
android:iconTint="#color/colorPrimary"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"/>
MainActivity.java
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.search:
getSupportFragmentManager().beginTransaction()
.replace(R.id.navHostFragment, new ContaFragment())
.commit();
break;
}
return false;
}
});
try adding the fragment to backstack
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.navHostFragment, fragment);
ft.addToBackStack(backStateName);
ft.commit();
}
}
this question has a good answer and explanation here How to resume Fragment from BackStack if exists

Trying To Open Up A New Screen/Activity In Android

I am trying to switch to a new screen when the user clicks on one of the options. This code is nested in the main activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about_settings:
Log.d("tcc", "This is getting to the about fragment");
startActivity(new Intent(MainActivity.this, HelpFragment.class));
return true;
case R.id.help_settings:
Log.d("tcc", "This is getting to the help fragment");
startActivity(new Intent(MainActivity.this, SettingsFragment.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I am then trying to get it to switch to one of the fragments that I have created. When I do this though I am getting an error:
Unable to instantiate activity ComponentInfo{info.hccis.bookingapplication/info.hccis.bookingapplication.SettingsFragment}: java.lang.ClassCastException: info.hccis.bookingapplication.SettingsFragment cannot be cast to android.app.Activity
You want to do Fragment Transactions not startActivity :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.about_settings:
Log.d("tcc", "This is getting to the about fragment");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new HelpFragment());
fragmentTransaction.addToBackStack(null); // to provided navigation when back is clicked
fragmentTransaction.commit();
return true;
case R.id.help_settings:
Log.d("tcc", "This is getting to the help fragment");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new SettingsFragment());
fragmentTransaction.addToBackStack(null); // to provided navigation when back is clicked
fragmentTransaction.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And define a fragment coinainer/which will be replaced by your
fragments: in your Activity's View:
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

Bottom navigation bar stop a fragment running when another one is opened

So I have no idea how to do this and even where to start, so if someone would be patient enough to explain how to do this I would be appreciated.
I already looked up on google but what I found was too difficult to understand ( and I am pretty sure that it can be done way more easily.
I have 4 fragments (4 tabs on a bottom navigation bar) and I want to have only 1 running at the time.
Now, I am pretty sure that I should use FragmentManager but I don't really know how to start to implement in my program.
Do I have to write all the FragmentTransaction code in the mainActivity? and after that how to keep goin? Is there a example code by any chance?
Disclaimer: I am a total noob in the android studio environment and I am also a student and I almost do everything as a school project.
You Can try this in your code. On the onNavigationItemSelected
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
fragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
I hope this can help You!
Thank You.

How to use onBackPress button in fragment on Android

In my application I have NavigationView and into this NavigationView I have set menu for open some fragments!
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="320dip"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#000"
android:fitsSystemWindows="true"
app:headerLayout="#layout/tester_drawer_header"
app:itemIconTint="#fff"
app:itemTextColor="#fff"
app:menu="#menu/tester_drawer_main"/>
I want when click on this menu open one fragment and I want when go to nested fragments and press onBack button open first fragment not open backStack fragments!
I write below codes, but after click on back button back fragments from backStack, but I want just open first fragment!
MyActivity codes:
public class TesterDashboardActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tester_dashboard);
loadFragment(new TesterTestListFragment(), userName);
}
#Override
public void onBackPressed() {
fragmentBackCount = getSupportFragmentManager().getBackStackEntryCount();
if (fragmentBackCount <= 1) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
//finishAffinity();
super.onBackPressed();
}
} else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
loadFragment(new TesterTestListFragment(), userName);
break;
case R.id.nav_billing:
loadFragment(new TesterFinanceFragment(), context.getString(R.string.menu_billing));
break;
case R.id.nav_edit_profile:
loadFragment(new TesterProfileFilterEditFragment(), context.getString(R.string.menu_edit_profile));
break;
case R.id.nav_bank:
loadFragment(new TesterShebaFragment(), context.getString(R.string.menu_bank));
break;
case R.id.nav_report:
loadFragment(new TesterReportsFragment(), context.getString(R.string.menu_report));
break;
case R.id.nav_setting:
loadFragment(new TesterSettingFragment(), context.getString(R.string.menu_setting));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void loadFragment(Fragment fragment, String toolbarTitle) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.testerFragment, fragment,TAG_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
toolbar.setTitle(toolbarTitle);
}
How can I fix it?
In your code I found when the fragmentBackCount>1 you just call getSupportFragmentManager().popBackStack(); once, so you will see top fragment on backstack.
I think you should call getSupportFragmentManager().popBackStack();, fragmentBackCount-1 time to reach the first fragmnet
else {
for(int i=0;i<fragmentBackCount-1;i++)
getSupportFragmentManager().popBackStack();
}
When you are transitioning between Fragments, call addToBackStack() as part of your
FragmentTransaction:
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();

Display fragments with Navigation Drawer

I'm confused how to open my different fragments by clicking on one Item in my navigation drawer.
In MainActivity I use the following Code:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment;
int id = item.getItemId();
if (id == R.id.nav_listview) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment, new ListFragment());
ft.commit();
} else if (id == R.id.nav_add_data) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_legal_information) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
First of all I want to try to open my ListFragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
}
In my content main.xml I created the following fragment which should be replaced when clicking on the specific Items in the Navigation Drawer.
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fragment" />
But it isnt working...
Can anyone help me?
Rastaman
To get what you want try this ,I was also held up with this somewhat complex looking code but its more of a easy way to use
Here's detailed explanation and walk through to this issue:
(Its seems Long But You can easily relate your work asap)
When you first create the Navigation Drawer Activity, there are 5 files we’ll look at:
MainActivity.java - this is the code behind for everything in our app.
activity_main.xml - this is the layout for the app including the nav drawer and an include for the app_bar_main.
app_bar_main.xml - this is the layout with the toolbar (at the top), a floating action button (at the bottom right), and an include for content_main.
content_main.xml - this is the layout for the content of the main page.
nav_header_main.xml - this is the UI for the top part of the nav drawer.
Step 1:
open up the app_bar_main.xml, comment out the include and add a new FrameLayout:
<!--<include layout="#layout/content_main" />-->
<FrameLayout
android:id="#+id/Fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"/>
This FrameLayout is what we’ll use to load our fragments into.
Step 2:
Next, you’ll want to add a few fragments
To do so, right click on your project, or go to File –> New and from the Fragment list choose Fragment (Blank) or others
Step 3:
The next step is to load a fragment when the app first launches. Go to the MainActivity’s onCreate method and put the following in after the call to setSupportActionBar:
Fragment fragment = null;
Class fragmentClass = null;
fragmentClass = FragmentOne.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.Fragment_container, fragment).commit();
Step 4:
You’ll then need to add OnFragmentInteractionListener to the interfaces your MainActivity implements and also implement the onFragmentInteraction method.Like this
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentOne.OnFragmentInteractionListener ,FragmentTwo.OnFragmentInteractionListener,FragmentThree.OnFragmentInteractionListener {
Step 5:
Finally, in the onNavigationItemSelected method, you can add the ability to load different fragments when menu items are tapped:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
Class fragmentClass = null;
if (id == R.id.nav_camera) {
fragmentClass = FragmentOne.class;
} else if (id == R.id.nav_gallery) {
fragmentClass = FragmentTwo.class;
} else if (id == R.id.nav_slideshow) {
fragmentClass = FragmentThree.class;
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Here I’m just loading one of the two fragments I’ve added to my app. Note that because I have two different fragments, I had to implement the interfaces for both FragmentOne.OnFragmentInteractionListener and FragmentTwo.OnFragmentInteractionListener.
That’s all you need to do to implement fragment loading in your Navigation Drawer.
What the user taps a menu item, the drawer will slide back in smoothly and the new fragment will have already started / finished loading. This also prevents any possible jankiness that you could see when launching a new activity.
EXTRA
One last thing to note is that if you switch to a different fragment and then rotate the device or cause another recreation of the activity, the code above will cause the first fragment to be reloaded. One easy way to deal with that is to wrap the fragment block in the onCreate method in a check to see if the savedInstanceState is not null like this:
protected void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState == null) {
//Fragment load code
}
...
}
Try this Code
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment=null;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_listview) {
fragment= new ListFragment();
} else if (id == R.id.nav_add_data) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_legal_information) {
}
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/container" />
Please Change The name of your fragment class ListFragment Because ListFragment is already Sub Class of Fragments in android.app package android OS
Mhmm I found an answer. But I am confused.
If I use:
if (id == R.id.nav_listview) {
fragment= new com.thomas.testapp.ListFragment();
It works. But I only have to use the package name if I want to open my ListFragment. Why?
I suggest to Create codes More Dynamic
first of all, if you have custom class to create Navigation Drawer, use listener to call methods from your activity
there is class call HomeFragment extends Fragment, so we have :
if(condition){
fragment = new HomeFragment();
// if there is Listener
if(mListener != null){
mListener.someMethod
}
// Other Settings And Codes
}
public class MainActivity extends AppCompatActivity {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...From section above...
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
// ...
}

Categories