Android app: How to change fragments in Navigation Drawer - android

First of all I'm new to android developement and also to java.
I created a new project with the fragment navigation drawer,
but I don't really know how to add and change to those new fragments with it.
(It also seems like it doesnt change any fragments, just sets the TextView to a the selected position.)
Do you guys may know a good tutorial on how to do that (step by step)?
Or can you please give me a hint on how to do it?
EDIT:
I found a solution by myself:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch(position){
case 0:
fragment = new Fragment_main().newInstance(position+1);
break;
case 1:
fragment = new Fragment_two().newInstance(position+1);
break;
default:
fragment = new Fragment_main().newInstance(position +1);
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
you just have to add a switch into this method, and also create those classes (and layouts).
I hope this solution helps everyone who also struggles as begginer or with the navigation drawer :)

I found a solution by myself:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch(position){
case 0:
fragment = new Fragment_main().newInstance(position+1);
break;
case 1:
fragment = new Fragment_two().newInstance(position+1);
break;
default:
fragment = new Fragment_main().newInstance(position +1);
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
you just have to add a switch into this method, and also create those classes (and layouts).
I hope this solution helps everyone who also struggles as begginer or with the navigation drawer :)

Related

Replace fragments in FrameLayout layout

I have tried every tutorial on the first google page about android fragments, but I can't get anything to work.
So I have one navigation bar activity, MainActivity.
Now I'd like to change fragments on a click in the drawer.
In my content_main (default fragment in the MainActivity activity), I have a framelayout that I wish to put the fragments in. I have the following fragments: fragment_main, fragment_one and fragment_two. And I wish to show these when I click on a button in the nav drawer.
The reason I want to use fragments is so that the nav drawer will stay on top.
Thanks in advance!
Edit: Here is the function I'll use to change fragments:
It's just to test, not finished.
public void setFragment() {
android.support.v4.app.FragmentTransaction transaction;
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, new LoginFragment());
transaction.commit();
}
I solved it!
Apparently, I had to use android.support.v4.app.Fragment; instead of android.app.Fragment;.
This is the code I got it to work with:
protected void setFragment(Fragment fragment) {
android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.fragment_container, fragment);
t.commit();
}
And to set it (from the nav bar onNavigationItemSelected(), you do this:
setFragment(new RoosterFragment());
I hope this helps others out with the same frustrating problem.
Accroding to your question,
This is FrameLayout
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/view"
android:layout_marginTop="#dimen/medium_margin"></FrameLayout>
Now , call displayview method onCreate() of your activity,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//rest of your code here
displayView(0); // fragment at 0 position
}
displayView method, which have three fragements
public void displayView(int position) {
switch (position) {
case 0:
tvTitle.setText(getResources().getString(R.string.signin_tile));
showFragment(new LoginFragment(), position);
break;
case 1:
tvTitle.setText(getResources().getString(R.string.forgot_password_tile));
showFragment(new ForgotPasswordFragment(), position);
break;
case 2:
tvTitle.setText(getResources().getString(R.string.change_password_tile));
showFragment(new ChangePasswordFragment(), position);
break;
}
}
showFragment method called from displayView method,
public void showFragment(Fragment fragment, int position) {
FragmentTransaction mTransactiont = getSupportFragmentManager().beginTransaction();
mTransactiont.replace(R.id.main_container, fragment, fragment.getClass().getName());
mTransactiont.commit();
}
Did you try this? Click here
This link will Help you, to create fragment.
and this is what you want for navigation drawerClick here
Try this one. it is my newbie code easier to understand :)
FragmentTransaction transaction;
switch (id){
case R.id.button_fragment_one:
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, new FragmentOne());
transaction.addToBackStack(null);
transaction.commit();
break;
case R.id.button_fragment_two:
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, new FragmentTwo());
transaction.commit();
break;
default:
break;
}

how to open google map in fragment using custom navigation drawer

I have used the following codings:
For Custom Navigation Drawer:
http://www.tutecentral.com/android-custom-navigation-drawer/
For Google Map:
http://wptrafficanalyzer.in/blog/showing-nearby-places-with-photos-at-any-location-in-google-maps-android-api-v2/
I'm new in android so please tell me how to link the the custom navigation drawer with google map.
I think you didn't get the answer for this question. If you post your code, i can be more helpful. but, for now, I think you need to call MapFragment in your NavigationDrawer Activity.
If you need the map only for one fragment, I suggest you to use a switch statement.
Following shows a sample code.
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MapFragment();
break;
case 1:
fragment = any of your fragment();
break;
case 2:
fragment = any of your fragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mLenear);
}
else {
// error in creating fragment
Log.e("Extract", "Error in creating fragment");
}
}
Hope this helps.

How can i get the current Fragment ID

I did a navigation drawer, and I’ve set some items and normally when I select an item the current fragment will be changed by a new one, it's not the case for me, the first Activity still displayed even if the fragments change. This is my onNavigationDrawerItemSelectedmethod and it's clear I change the fragment every time i click on a new one.
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
// TODO : Added
switch(position) {
/*case 0 :
fragmentManager.beginTransaction()
.replace(R.id.container, new ProfilFrgement())
.commit();
break;*/
case 1:
fragmentManager.beginTransaction()
.replace(R.id.container, new SpotFragement())
.commit();
break;
case 2:
fragmentManager.beginTransaction()
.replace(R.id.container, new SessionsFragement())
.commit();
break;
/*case 3:
fragmentManager.beginTransaction()
.replace(R.id.container, new EventsFragment())
.commit();
break;*/
}
}
I think my problem is a change always the same container. So what I need its getting the current fragment ID
Sorry for too late but I have a solution to get fragment ID. You can use name of Fragment Class as an Identifier not the ID. Use a static String variable to store class name.
public class Activity{
...
static String currentFragment = null;
...
...
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_one:
setFragment(new oneFragment());
break;
case R.id.nav_two:
setFragment(new twoFragment());
break;
}
return true;
}
public static void setFragment(#NonNull Fragment f) {
if(!f.getClass().getName().equals(currentFragment)){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, f);
fragmentTransaction.commit();
currentFragment = f.getClass().getName();
}
...
}
What is current fragment ID here? Ur id is R.id.container which is only one rt? then what is the question about "How can i get the current Fragment ID"?
If question is to find which is the current fragment is shown to user? If yes then
Fragment ft = getSupportFragmentManager().findFragmentById(R.id.container);
if (ft instanceof SpotFragement) {
// navigation drawer item 1 and current fragment is SpotFragment.
} else if (ft instanceof SessionsFragement) {
}
Make sure that your container styling is correct.
Check following values of container once -
android:layout_width
android:layout_height

Replace a Fragment created from Navigation Drawer with another dynamically

I have a navigation drawer that works well. By well I mean I can navigate through all the fragments tied to the Navigation drawer (A,B,C,D). My issue arises here. Lets say am in Fragment A, in this fragment I have a button which on clicking should ideally replace the fragment with another one say Frag Z, and once I am in Frag Z I can return back to frag A.
To achieve this I use the below code. However the new fragment Z appears transparent on top of Fragment A. What could be the problem:
Bundle bundle = new Bundle();
bundle.putInt("int", 1);
bundle.putString("str","string" );
fragmentTransaction = getFragmentManager().beginTransaction();
FragZ fragmentz = new FragZ();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.some_container, fragmentz);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
EDIT:
I have found a workaround to this as shown below,however it does not completely solve my problem since the newly displayed fragment is still shown with the navigation drawer capable of being toggled,but it atleast removed the overlaying of the fragments. I would still want a solution to launching an independent fragment
Bundle bundle = new Bundle();
bundle.putInt("int", 1);
bundle.putString("str","string" );
FragZ fragmentz = new FragZ();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
fragment.setArguments(bundle);
ft.replace(R.id.main, fragment);
ft.addToBackStack(null);
ft.commit();
Create a method in your activity to launch fragments. Whenever you want to display the fragment, just call in with a number or string to represent the fragment. You can use the same function to launch fragments from your navigation drawer.
For example:
public void displayView(int position) {
Fragment fragment = null;
currentFragmentNumber = position;
switch (position) {
case 0:
fragment = new frag1();
break;
case 1:
fragment = new frag2();
break;
case 2:
fragment = new frag3();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment)
.addToBackStack("tag").commit();
} else {
// error in creating fragment
Log.e(TAG, "Error in creating fragment");
}
}
You can call this function from your activity by using:
((**ActivityName**) getActivity()).displayView(0);

Fragment removes when Orientation changes

I am using fragment in my application. When I change the orientation the fragment removes and my main activity gets visible from which I have added this fragment. below is the code -
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ManageDataFragment();
break;
case 1:
fragment = new DownloadFragment();
break;
case 2:
fragment = new UserInfoFragment();
break;
case 3:
fragment = new AboutAppFragment();
break;
case 4:
fragment = new ShareAppFragment();
break;
case 5:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
I am using this fragment from navigationDrawer like in Gmail application.
What should I do that my fragment remains even I change the orientation of device?
Thanks in Advance
I don't think the accepted answer is the correct so I'm writing this one:
When replacing the fragment you should use the method replace with three arguments so you can find your fragment later:
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, TAG_FRAGMENT).commit();
Where TAG_FRAGMENT is some string tag.
Then in onCreate if the activity was restarted you can find your fragment and add it to the container:
if(savedInstanceState != null) {
fragment = getFragmentManager().findFragmentByTag(TAG_FRAGMENT);
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, TAG_FRAGMENT).commit();
}
I had exactly the same problem as mentioned above and I fixed it in the AndroidManifest by adding this:
<activity
...
android:configChanges="orientation|screenLayout|screenSize|layoutDirection">
Hope this helps!
Probably should save position using onSaveInstanceState() and test the bundle argument to onCreate().

Categories

Resources