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.
Related
I have a app with a main activity and fragments. My fragments work but when I switch between them, they refresh and create a new fragment when I switch back. I want the data to save when I switch back and forth, but I can't figure out how to use a bundle to save the values.
This is the code that controls switching between fragments:
`private NavigationBarView.OnItemSelectedListener navListener =
new BottomNavigationView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;//used to default to home
if(item.getItemId() == R.id.nav_home){
selectedFragment = new HomeFragment();
}else if(item.getItemId() == R.id.nav_input){
//selectedFragment = new InputFragment();
if((InputFragment) getSupportFragmentManager().findFragmentByTag("input_tag") != null){
selectedFragment = (InputFragment) getSupportFragmentManager().findFragmentByTag("input_tag");
}else{
selectedFragment = new InputFragment();
}
}else if(item.getItemId() == R.id.nav_balance){
selectedFragment = new BalanceFragment();
}else if(item.getItemId() == R.id.nav_calendar) {
selectedFragment = new CalendarFragment();
}
if(selectedFragment == null) selectedFragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment, "input_tag").commit();
return true;
}
};
}`
I tried reformatting it, and looked through Android Studio forums, but I can't seem to find anything helpful to resolving this problem. I unsuccessfully tried to use tags to save a fragment, but it didn't retain the data. I also tried to use savedInstanceState but it did not work. Any help or directions to start in would be greatly appreciated.
I'm having the problem that when I trying to switch between the menu item. The menu item will not pointing to the correct icon.
here is the flow when i found this problem
starting at the (Home)fragment,then press on the second menu item (Features )
case R.id.nav_home:
//home fragment transaction
actionBar.setTitle("Home");
HomeFragment fragment1 = new HomeFragment();
FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.content, fragment1, "");
fragmentTransaction1.commit();
break;
second menu item (features) will go to features activity
case R.id.nav_features:
//features fragment transaction
startActivity(new Intent(DashboardActivity.this, FeaturesActivity.class));
break;
close features activity and back to (Home) fragment
onBackPressed();
bottom navigation still pointing to second menu item (features).
how can I make the system point to the correct menu item ?
You should return a boolean for this method:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//...
}
do this :
case R.id.nav_home:
//home fragment transaction
actionBar.setTitle("Home");
HomeFragment fragment1 = new HomeFragment();
FragmentTransaction fragmentTransaction1 =
getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.content, fragment1, "");
fragmentTransaction1.commit();
return true; // add this line and remove break;
if you don't want to select icon after click, you can return false.
I'm making an app that has launches with a Swiping Tabs Fragment, but I also want to have a Preferences menu using Fragment Transaction. When I press the Settings button in my app, the preferences menu does appear and is interactive, but the layout seems to be transparent showing the Tabs below. Is there anything that can be done to fix this, or is there a better method?
Code that calls the Preferences Menu from the Options:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
break;
case R.id.logout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, Activity_Main.class));
break;
case R.id.action_settings:
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new Fragment_Settings()).addToBackStack(null)
.commit();
break;
}
return true;
}
Code that calls Tabs Fragments:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Fragment_Flower();
case 1:
// Games fragment activity
return new Fragment_Overview();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
Initialising Transaction in onCreate:
startService(new Intent(this, SensorListener.class));
if (b == null) {
// Create new fragment and transaction
Fragment newFragment = new Fragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
Any help will be greatly appreciated!
Just set background color in your layout file. It may avoid transparent backgound.
I am developing an Android Application with navigation activity and there are some list of options in navigation drawer and my First page is also in this activity. I am navigating to another page through the options present in the navigation drawer which are Fragment classes. I need to come back to the first page if I press back button on device. But it goes to pages which I visited before. My Target is to come back to First page from the respective Fragment class.
At times when I hit back button, it also comes to my splash screen, Kindly help me to fix this. Thanks in advance.
This is the code of my FirstPage from where I am navigating to another pages through drawer. I need to come back to this same page again from the drawer (FirsPage)
public void selectDrawerItem(MenuItem menuItem) {
switch(menuItem.getItemId()) {
//1.User Profile
case R.id.navigation_item_attachment:
fragmentClass = ProfileTab.class;
// finish();
break;
//2.FeedBack
//case R.id.navigation_item_images:
/* fragmentClass = SearchHistoryTab.class;
break;*/
case R.id.navigation_refer:
fragmentClass = ReferFrndz.class;
// finish();
break;
case R.id.navigation_daily:
fragmentClass = DailyUsage.class;
break;
//4.About Us
case R.id.navigation_about:
fragmentClass = AboutJc.class;
break;
//4.Contact Us
case R.id.navigation_item_location:
fragmentClass = ContactJc.class;
break;
default:
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.search_layout, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
I used Finish() but it didn't work. It terminating my entire application.
Splash Screen Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread mythread = new Thread() {
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}
finally {
.....
}
}
}
};
mythread.start();
}
Update your Fragmenttransaction code to add ProfileTab (FirstPage) in backstack entry.' So you get ProfileTab (FirstPage) back after click back button.
FragmentManager fragmentManager = getSupportFragmentManager();
if(fragment.equals(ProfileTab.class)){
fragmentManager.beginTransaction().replace(R.id.search_layout, fragment).addToBackStack("fragment_tag").commit();
//Only add backstack entry for first page so you get after click on back button
}
else
{
fragmentManager.beginTransaction().replace(R.id.search_layout, fragment).commit();
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
Use this solution and share your feedback with replay will help us to improve solution.
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();