I have a navigation drawer and when I click on one of the menus, I want the default content to disappear, but it just doesn't happen and when I click on a new menu it's still there.
This is really annoying, I've been trying to find solution the whole day and I'm going crazy now.
Please help me out, if you can. Thanks in advance!
I copy the whole code here. (p.s.: this is the first and last time I'm programming on Android, this is a nightmare...I just must do this now :/)
public class About extends AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
ImageButton FAB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
FAB = (ImageButton) findViewById(R.id.imageButton);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(About.this, SecondActivity.class);
startActivity(i);
//FAB click, call other thing...
}
});
navigationView = (NavigationView) findViewById(R.id.nav_view);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new ListViewFragment());
fragmentTransaction.commit();
setNavDrawer();
navigationView.setCheckedItem(R.id.nav_gallery);
}
private void setNavDrawer() {
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_camera:
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction f = getSupportFragmentManager().beginTransaction();
f.replace(R.id.content_frame, fragment);
f.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.nav_gallery:
Toast.makeText(getApplicationContext(), "Whatever", Toast.LENGTH_SHORT).show();
UserFragment fragment2 = new UserFragment();
android.support.v4.app.FragmentTransaction f2 = getSupportFragmentManager().beginTransaction();
f2.replace(R.id.content_frame, fragment2);
f2.commit();
return true;
case R.id.nav_slideshow:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_share:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(), "SOON", Toast.LENGTH_SHORT).show();
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.addDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.about, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Use these code on menu click..
Fragment fragment = new ContentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.remove(new CurrentFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
an also add these lines in xml
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Try this
Fragment fragment = new Fragment();
fragment.setRetainInstance(true);
fragment = new ContentFragment ();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
Related
In my app I have created a Navigation Drawer with six Fragments. The MainOption Fragment is not included in the Navigation item menu list. Now I want to activate Back button on mobile device to redirect to Main Fragment. For example if I have fragments A,B,C,D,E,F, and now if I click B, then if I press back button, it will back to A. In the same way if I Press back button on Fragment E it will redirect to Fragment A. Now how can I achive this logic in my code. Hence I have tried lots of code from the website, but nothis was working at all. Here is my code snepet for Navigation Drawer
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private Toolbar toolbar ;
private View navigationHeader;
private ImageView imgProfile;
private TextView txtName, txtWebsite;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navigationHeader= navigationView.getHeaderView(0);
txtName = navigationHeader.findViewById(R.id.username);
txtWebsite = navigationHeader.findViewById(R.id.email);
imgProfile = navigationHeader.findViewById(R.id.profile_image);
// load nav menu header data
loadNavHeader();
//Set the Home Fragment initially
OptionMenuFragment fragment = new OptionMenuFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
fragmentTransaction.commit();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void loadNavHeader() {
// name, website
txtName.setText("Hallo");
txtWebsite.setText("mail.com");
imgProfile.setImageResource(R.drawable.profile_image);
//ToDo: Image should be uploaded from web
}
String lastFragmentTag;
boolean showingFirstFragment = true;
public void addNewFragment(Fragment fragment, String fragmentTag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (lastFragmentTag != null) {
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
} else {
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
transaction.hide(currentFragment);
}
transaction.add(R.id.fragment_container, fragment, fragmentTag);
transaction.commit();
lastFragmentTag = fragmentTag;
showingFirstFragment = false;
}
#Override
public void onBackPressed() {
//Here we're gonna remove the last fragment added, and show OptionMenuFragment again
if (!showingFirstFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
transaction.show(firstFragment);
transaction.commit();
showingFirstFragment = true;
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.blu_home) {
Intent intent = new Intent(this, MainOptionPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
String fragmentTag=null;
// Handle navigation view item clicks here.
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.view_profile:
fragment = new ViewProfileFragment();
fragmentTag = "ViewProfileFragment";
break;
case R.id.todo_list:
fragment =new ToDoListFragment();
fragmentTag="ToDoListFragment";
break;
case R.id.logout:
showAlertDialogLogOut();
break;
case R.id.settings:
fragment = new SettingsFragment();
fragmentTag="SettingFragment";
break;
case R.id.about:
fragment = new AboutFragment();
fragmentTag="AboutFragment";
break;
case R.id.info:
fragment=new InfoFragment();
fragmentTag="InfoFragment";
break;
}
if(fragment!=null){
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void showAlertDialogLogOut() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Logout");
builder.setMessage("Are you sure you want to log out?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
dialog.dismiss();
startActivity(new Intent(MainOptionPage.this, LoginPage.class));
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
For that approach, you will want to use the add(containerViewId, fragment, tag) method instead of replace(containerViewId, fragment), since replace will call remove(Fragment) for ALL fragments previously added to the container, before adding the new fragment. Also, you will want to use addToBackStack(name).
Here's a method I created for a project, and slightly modified for you:
String lastFragmentTag;
boolean showingFirstFragment = true;
public void addNewFragment(Fragment fragment, String fragmentTag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (lastFragmentTag != null) {
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
} else {
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
transaction.hide(currentFragment);
}
transaction.add(R.id.fragment_container, fragment, fragmentTag);
transaction.commit();
lastFragmentTag = fragmentTag;
showingFirstFragment = false;
}
Then you just have to make this change inside onNavigationItemSelected:
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
String fragmentTag;
switch (item.getItemId()) {
case R.id.view_profile:
fragment = new ViewProfileFragment();
fragmentTag = "ViewProfileFragment";
break;
...
}
if(fragment!=null){
addNewFragment(fragment, fragmentTag);
}
Where "fragmentTag", is going to be a String variable which you change according to the fragment instantiated.
EDIT: Some more changes since the code wasn't working as intended:
#Override
public void onBackPressed() {
//Here we're gonna remove the last fragment added, and show OptionMenuFragment again
if (!showingFirstFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment firstFragment = fragmentManager.findFragmentByTag("OptionMenuFragment");
Fragment currentFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
transaction.remove(currentFragment);
transaction.show(firstFragment);
transaction.commit();
showingFirstFragment = true;
} else {
super.onBackPressed();
}
}
And when adding OptionMenuFragment, do this instead:
fragmentTransaction.replace(R.id.fragment_container, fragment, "OptionMenuFragment");
In my app, I have a NavigationDrawer in my app that has two fragments I want to display (Fragment1 and Fragment2) in a MainActivity. I have a menu item in my ToolBar in Fragment 1 when clicked I want to my MainActivity to switch to Fragment2 and have the NavigationView reflect the UI changes.
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, new BookListFragment()).commit();
}
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
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.book_list_fragment:
fragmentClass = BookListFragment.class;
break;
case R.id.discover_fragment:
fragmentClass = DiscoverFragment.class;
break;
default:
fragmentClass = BookListFragment.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();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Fragment Code
public class BookListFragment extends Fragment {
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_insert_dummy_data:
insertBook();
return true;
case R.id.action_delete_all_entries:
int rowsDeleted = getContext().getContentResolver().delete(ShelfHelpContract.BookEntry.CONTENT_URI, null, null);
return true;
case R.id.action_discover:
/*TODO Here I want to open another Fragment and have it reflect
in the UI on my NavigationView and MainActivity
*/
return true;
}
return super.onOptionsItemSelected(item);
....
}
The following code takes care of replacing your Fragment when the user clicks on one of the navigation items
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
Besides replacing the fragment you will want to also update the title of your activity using something along the lines of:
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Home");
And finally you must tell your NavigationView to highlight the right item using the setChecked(boolean) function. It should look something like this:
nvDrawer.getMenu().findItem(/*your item id*/).setChecked(true);
If you want to perform the same action when the user clicks on a menu item then make sure to add a new case to the switch block found in your onOptionsItemSelected(MenuItem item) and just call the same lines passing in the right Fragment
I want to implement onBackPress to my fragment but i don't know how. When i go to another fragment (in this case, my fragment is the one from my ActivityHome and i'm using standard NavigationDrawer from android stuudio).
Here is my code for ActivityHome
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentHome fragment = new FragmentHome();
fragmentTransaction.add(R.id.containerID, fragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
Toast.makeText(getApplicationContext(),
"Akun anda telah dikeluarkan!", Toast.LENGTH_LONG).show();
Intent logout = new Intent(ActivityHome.this, ActivityMain.class);
startActivity(logout);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.nav_home){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, FragmentHome.newInstance()).commit();
}else if (id == R.id.nav_profile){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, Profile.newInstance()).commit();
}
else if (id == R.id.nav_history){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, History.newInstance()).commit();
}
else if (id == R.id.nav_about_us){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, AboutUs.newInstance()).commit();
}
else if (id == R.id.nav_ganti_kata_sandi){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, GantiKataSandi.newInstance()).commit();
}
else if (id == R.id.nav_share){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, Share.newInstance()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I hope u guys can help me with my problem.
I have webview in fragment, I used this code to detect backpress code in mainactivity OnbackPressed():
Fragment webview = getSupportFragmentManager().findFragmentByTag("BLOG");
if (webview instanceof BlogFragment) {
boolean goback = ((BlogFragment) webview).canGoBack();
if (!goback) {
} else {
((BlogFragment) webview).goBack();
}
}
Make sure you start fragment like:
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.frame_content, new BlogFragment(), "BLOG")
.commit();
To open fragment from activity.
Fragment fragment = Fragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter,
R.anim.fragment_slide_right_exit);
addFragmentToActivity(fragmentTransaction, Fragment, R.id
.content_frame);
public void addFragmentToActivity(#NonNull FragmentTransaction transaction,
#NonNull Fragment fragment, int frameId) {
transaction.addToBackStack(fragment.getClass().getName());
transaction.add(frameId, fragment, fragment.getClass().getName());
transaction.commit();
}
That's how I add fragment from HomeActivity and For back Call override method OnBackPressed in HomeActivity.
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStackImmediate();
}
You can get event when back button pressed from any fragment in Activity's onBackPressed() method.
Suppose you've pressed back from HomeFragment then you can get onBackPressed in Activity like following :
#Override
public void onBackPressed() {
HomeFragment fragment = (Fragment)findFragmentById(// fragment id);
if(fragment!=null && fragment.isVisible()){
// Here you can code for Home Fragment's onBackPress()
}
super.onBackPressed();
}
When i press back button from my Home_Fragment the control will go to a empty page ,i want to exit my application when i press back button from Home_Fragment,at the same time when i press back button from all other fragment i want to navigate to Home_Fragment. My MainActivity page is below.
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
you can write code for onBackButton to check for count of BackStackEntry. if atleast one fragement is in it, Count will be more than 0.
if count==0 then do finish()
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() == 1) {
//no fragments left
finish();
} else {
super.onBackPressed();
}
}
You can try this, It works:
Create a method in main Activity to call fragment:
public void replaceFragment(Fragment fragmentName){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragmentName);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
And call this method by any fragment by the following lines of code:-
((MainActivity)getActivity).replaceFragment(FragmentName.class)
I have created MainActivity with NavigationView. When Activity is opened I want to automatically select the first item in the navigation drawer and open Fragment under that item. I've searched a lot but didn't find any proper solutions.
What is the proper way to do this ?
Main Activity:
public class MainActivity extends AppCompatActivity implements Config {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(getResources().getColor(R.color.colorIcons));
if (null != getSupportActionBar())
getSupportActionBar().setLogo(R.drawable.ic_blogger_white);
//Start PostListFragmentWebView
/*PostListFragmentWebView postListFragmentWebView = new PostListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, postListFragmentWebView)
.commit();*/
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigationView);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not set it to checked state.
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was clicked and perform the appropriate action.
switch (menuItem.getItemId()) {
case R.id.posts:
PostListFragmentWebView postListFragment = new PostListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, postListFragment)
.commit();
return true;
case R.id.pages:
PageListFragmentWebView pagetListFragment = new PageListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, pagetListFragment)
.commit();
return true;
case R.id.blog:
BlogInfoFragmentWebView blogInfoFragment = new BlogInfoFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, blogInfoFragment)
.commit();
return true;
default:
Toast.makeText(getApplicationContext(), getResources().getString(R.string.drawer_error), Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we don't want anything to happen so we leave this blank.
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank.
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.getChildAt(0).setSelected(true);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
}
In onCreate(), following code will load the first item's fragment upon first start:
if (savedInstanceState == null) {
navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
}
Thanks to calvinfly for this comment.
Add android:checked="true" to your first menu item.
And manually select one item, using
getSupportFragmentManager().beginTransaction().replace(R.id.frame, postListFragment).commit();
to open fragment.
Instead of normal listener ...
navView.setNavigationItemSelected(new Navigation.View.OnNavigationItemSelectedListener() {bla, bla, bla})
Create the listener as an Obj:
NavigationView.OnNavigationItemSelectedListener navViewListener;
navView.setNavigationItemSelectedListener(navViewListener = new NavigationView.OnNavigationItemSelectedListener() {bla, bla, bla})
...and use the Obj to trigger the listener event:
navViewListener.onNavigationItemSelected(navView.getMenu().getItem(0));
...where getItem(0) is the first menu item.
Use a method getItem(0).setChecked(true) or android:checked="true" at its menu item XML definition.
You could also use navigationView.setCheckedItem(R.id.default)(javadoc) after you setup your navigationview.
just add this code in onCreate method:
FragmentTransaction ftrans = getFragmentManager().beginTransaction();
ftrans.replace(R.id.container, <yourfragment>).commit();
Work for me !
This can be done even better while considering orientation and other configuration changes. We could select whatever nav drawer menuitem depending on whether we are coming from a previous state. Check: For the Navigation drawer wielding Activity:-
public static final String SELECTED_NAV_MENU_KEY = "selected_nav_menu_key";
// The selected grid position
private int mSelectedNavMenuIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
...........................................................
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState != null) {
// Recover assets
mSelectedNavMenuIndex = savedInstanceState.getInt(SELECTED_NAV_MENU_KEY);
// Recover menu as selected
MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
toggleNavMenuItemCheck(menuItem);
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
return;
} else {
MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
toggleNavMenuItemCheck(menuItem);
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
}
}
The toggle method that helps uncheck or check the menu item
private void toggleNavMenuItemCheck(MenuItem menuItem) {
if (menuItem.isChecked()){
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
}
This is how I save the state of the selected menu item. Check:-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_explore:
showExploreFragment(null);
mSelectedNavMenuIndex = 0;
break;
case R.id.nav_orders:
mSelectedNavMenuIndex = 1;
break;
case R.id.nav_settings:
mSelectedNavMenuIndex = 2;
break;
default:
showExploreFragment(null);
mSelectedNavMenuIndex = 0;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
// Save any important data for recovery
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_NAV_MENU_KEY, mSelectedNavMenuIndex);
}
NB: The line with code:
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
Can be replaced by the code:
onNavigationItemSelected(menuItem);
in menu.xml remember to mention android:checkable="true" for single item and android:checkableBehavior="single" for a group of items.
<item
android:id="#+id/pos_item_help"
android:checkable="true"
android:title="Help" />
<group
android:id="#+id/group"
android:checkableBehavior="single">
<item
android:id="#+id/menu_nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/menu_nav_home" />
</group>
then inside NavigationItemSelectedListener use setCheckedItem(R.id.item_id_in_menu) to make it selected.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.pos_item_pos:
navigationView.setCheckedItem(R.id.pos_item_pos);
break;
case R.id.pos_item_orders:
navigationView.setCheckedItem(R.id.pos_item_orders);
break;
default:
}
return true;
}
And you do not have to do the dirty task of managing the selected item anymore. navigationView manages it by self.
1.) To land to the HomeFragment initially, use this inside your onCreate() in MainActivity:
Fragment fragment = new HomeFragment();
// replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
2.) To set the item as selected in navigationDrawer set the item as checked in navigation_menu.xml
android:checked = "true"