I'm building an app which contains a NavigationDrawer to navigate between Fragments.
For some reason, when pressing on any item in the Navigation Drawer the item just marks itself and doesn't change the fragment (tried debug but the item clicks doesn't calls the functions)
The fragment is not loading in first click..i have to press twice to reload the fragment
Main Activity:
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtCity;
private Toolbar toolbar;
private FloatingActionButton fab;
// urls to load user profile & background
private static final String urlNavHeaderBg = "";
private static final String urlProfileImg = "";
//current menu pressed
public static int navItemIndex = 0;
//tags for fragments
private static final String TAG_HOME = "home";
private static final String TAG_PROFILE = "profile";
private static final String TAG_RATEUS = "rate us";
private static final String TAG_SCORE = "rate score";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
private String[] activityTitles;
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();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
//nav view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtCity = (TextView) navHeader.findViewById(R.id.city);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
//load the toolbar titles
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Make action here", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
//load the navigator header data
loadNavHeader();
//initialize nav menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadNavHeader() {
txtName.setText("My Name");
txtCity.setText("Somewhere, Europe");
Glide.with(this).load(urlNavHeaderBg).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imgNavHeaderBg);
Glide.with(this).load(urlProfileImg).thumbnail(0.5f).bitmapTransform(new CircleTransform(this)).diskCacheStrategy(DiskCacheStrategy.ALL).into(imgProfile);
navigationView.getMenu().getItem(4).setActionView(R.layout.menu_dot);
}
private void loadHomeFragment() {
selectNavMenu();
setToolBarTitle();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
toggleFab();
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
ProfileFragment profileFragment = new ProfileFragment();
return profileFragment;
case 2:
RateusFragment rateusFragment = new RateusFragment();
return rateusFragment;
case 3:
ScoreFragment scoreFragment = new ScoreFragment();
return scoreFragment;
case 4:
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 5:
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolBarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setCheckable(true);
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_profile:
navItemIndex = 1;
CURRENT_TAG = TAG_PROFILE;
break;
case R.id.nav_rateus:
navItemIndex = 2;
CURRENT_TAG = TAG_RATEUS;
break;
case R.id.nav_score:
navItemIndex = 3;
CURRENT_TAG = TAG_SCORE;
break;
case R.id.nav_notifications:
navItemIndex = 4;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 5;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_terms:
startActivity(new Intent(MainActivity.this, TermsActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
//when nav closed this will triggered - leaving blank so nothing won't happen
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
//when nav opened this will triggered - leaving blank so nothing won't happen
super.onDrawerOpened(drawerView);
}
};
drawer.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
if (shouldLoadHomeFragOnBackPress) {
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
if (navItemIndex == 4) {
getMenuInflater().inflate(R.menu.notifications, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All marked as read!", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "All Cleared!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
tools:context=".activity.MainActivity">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
There are couple of problems with the code:
Make sure u add break in switch:
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
break; //add break
case R.id.nav_terms:
startActivity(new Intent(MainActivity.this, TermsActivity.class));
drawer.closeDrawers();
break;
default:
navItemIndex = 0;
break;
Also your fragment not loading as you are not calling the function properly:
in your Switch case:
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
Fragment fragment = getHomeFragment(); //get fragment based on index
ReplaceFragment(fragment); //now replace them and load new one
drawer.closeDrawers();
break;
in ReplaceFragment method write:
public void ReplaceFragment(Fragment r_fragment) {
if (r_fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, r_fragment).commit();
} else {
// error in creating fragment
}
}
Also overWrite following methods:
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
drawerView.bringToFront(); //add this two lines
drawerView.requestLayout();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
Related
I am receiving the following crash reports from fabric.io (mainly after I added a SettingsActivity which can be loaded from my SlidingMenue to my App):
The code of to post the pendingRunnable has not been changed recently, anyway it started to receive the exceptions.
Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
at my.app.ui.activity.MainActivity$2.run(MainActivity.java:271)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5530)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:733)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:623)
This is my MainActivity.java
public class MainActivity extends AppCompatActivity implements MyAppFragment.OnListFragmentInteractionListener, AsyncResponse {
private MyAppDatabaseHandler myAppDatabaseHandler;
private SharedPreferences sharedpreferences;
private SharedPreferences defaultPrefs;
private FragmentA fragmentA;
public static boolean activityVisible = true;
private boolean isAttached;
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private Toolbar toolbar;
// index to identify current nav menu item
private static int navItemIndex = 0;
public static String CURRENT_TAG = MyAppConstants.TAG_A;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// 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);
this.myAppDatabaseHandler= MyAppDatabaseHandler.getInstance(this);
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sharedpreferences = getSharedPreferences(MyAppConstants.PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
// Init UI
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.sliding_menu_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = MyAppConstants.TAG_A;
loadNextFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// Init NavigationHeader
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadNextFragment() {
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag( CURRENT_TAG) != null && navItemIndex != 4) {
drawer.closeDrawers();
return;
}
if (navItemIndex == 4) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
} else {
// set toolbar title
setToolbarTitle();
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the activity_main_header_with_item content by replacing fragments
Fragment fragment = getNextFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getNextFragment() {
switch (navItemIndex) {
case 0:
// home
return this.fragmentA;
case 1:
FragmentB fragmentB = new FragmentB();
return fragmentB;
case 2:
// About Fragment
AboutFragment aboutFragment = new AboutFragment();
return aboutFragment;
case 3:
// Licence Fragment
LicenceFragment licenceFragment = new LicenceFragment();
return licenceFragment;
default:
return this.fragmentA;
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void setUpNavigationView() {
//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) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the activity_main_header_with_item content with ContentFragment Which is our Inbox View;
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = MyAppConstants.TAG_A;
break;
case R.id.nav_recently:
navItemIndex = 1;
CURRENT_TAG = MyAppConstants.TAG_B;
break;
case R.id.nav_about_us:
navItemIndex = 2;
CURRENT_TAG = MyAppConstants.TAG_ABOUT;
break;
case R.id.nav_licences:
navItemIndex = 3;
CURRENT_TAG = MyAppConstants.TAG_LICENCES;
break;
case R.id.nav_settings:
navItemIndex = 4;
// do not set CURRENT_TAG
break;
default:
navItemIndex = 0;
}
loadNextFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#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
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress && CURRENT_TAG != MyAppConstants.TAG_A) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = MyAppConstants.TAG_A;
loadNextFragment();
return;
}
}
finish();
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_header_with_item, menu);
// Disable Player Icon in case no player is found on device
Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, MyAppConstants.MUSIC_APP);
List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
if(activities == null || activities.size() <= 0) {
MenuItem player = menu.findItem(R.id.player);
if(player != null){
player.setVisible(false);
}
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void notifyOnDelete(View v) {
myAppDatabaseHandler.deleteAll();
}
#Override
public void onListFragmentInteraction(Song item) {
}
#Override
public void processFinish(String output) {
if (isAttached) {
...
}
}
#Override
public void onAttachedToWindow() {
isAttached = true;
super.onAttachedToWindow();
}
#Override
public void onDetachedFromWindow() {
isAttached = false;
super.onDetachedFromWindow();
}
#Override
public void onResume() {
activityVisible = true;
updateFragmentA();
super.onResume();
}
#Override
public void onPause() {
activityVisible = false;
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
}
public void updateFragmentA() {
if (CURRENT_TAG == MyAppConstants.TAG_A) {
Timber.i( "updating FragmentA");
fragmentA.swap();
}
}
}
Any ideas about the cause of this issue?
Try this first setContentView(R.layout.activity_main); than perform your action
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.myAppDatabaseHandler= MyAppDatabaseHandler.getInstance(this);
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sharedpreferences = getSharedPreferences(MyAppConstants.PREFERENCES, Context.MODE_PRIVATE);
I have created a main activity which has a fragment container in it, I am replacing many fragments in it on navigation menu option select. Its working fine, but the problem is:
When I click a navigation item twice, two identical fragments open, i have to press the back button twice to go back.
When all fragments are destroyed after pressing back, I see an empty page (which may be main activity page I guess).
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/pageBackgroundColor"
tools:context="co.sd.app.MainActivity">
<RelativeLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/side_nav_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:padding="0sp"
app:menu="#menu/side_navigation_menu" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Bundle bundle;
private SessionManager session;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarToggle;
private TextView cartItemCountDisplay;
private NavigationView sideNavView;
private Menu sideNavViewMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.main_activity_page);
actionBarToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.OPEN, R.string.CLOSE);
drawerLayout.addDrawerListener(actionBarToggle);
actionBarToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bundle = new Bundle();
sideNavView = ((NavigationView) findViewById(R.id.side_nav_drawer));
sideNavViewMenu = sideNavView.getMenu();
//To Display Home Fragment On Page Load
displaySelectedItemResult(sideNavViewMenu.findItem(R.id.nav_home));
//To Adjust Login or Logout option in side navigation menu
if (session.isUserLoggedIn()) {
sideNavViewMenu.findItem(R.id.nav_login).setVisible(false);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(true);
} else {
sideNavViewMenu.findItem(R.id.nav_login).setVisible(true);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(false);
}
//Operation on side navigation item click
sideNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedItemResult(item);
//navDrawerLayout.closeDrawers();
return true;
}
});
}
private void displaySelectedItemResult(MenuItem item) {
sideNavViewMenu.findItem(R.id.nav_home).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_contactUs).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_aboutUs).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_login).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_logout).setChecked(false);
Fragment fragment;
switch (item.getItemId()) {
case R.id.nav_user:
if (session.isUserLoggedIn()) {
item.setTitle(session.getUserDetails().get(SessionManager.KEY_NAME));
} else {
item.setTitle("Login First!");
}
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_home:
fragment = new HomeFragment();
if (fragment != null) {
callNavMenuItemsFragment(fragment, "FRAG_HOME");
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_contactUs:
fragment = new ContactUsFragment();
if (fragment != null) {
callNavMenuItemsFragment(fragment, "FRAG_CONTACT_US");
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_aboutUs:
fragment = new AboutUsFragment();
if (fragment != null) {
callNavMenuItemsFragment(fragment, "FRAG_ABOUT_US");
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_login:
new UserAuthentication(MainActivity.this, session).loginAndSignupDialog();
sideNavViewMenu.findItem(R.id.nav_login).setVisible(false);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(true);
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_logout:
session.logoutUser();
sideNavViewMenu.findItem(R.id.nav_login).setVisible(true);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(false);
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
default:
}
}
private FragmentTransaction callNavMenuItemsFragment(final Fragment fragment, final String fragmentTag) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack(null);
//if (!ACTIVE_FRAGMENT_ID.equals(String.valueOf(fragment.getId()))) {
if (!activeFragmentIDsList.contains(String.valueOf(fragment.getId()))) {
ft.replace(R.id.fragment_container, fragment, fragmentTag);
activeFragmentIDsList.add(String.valueOf(fragment.getId()));
}
ft.commit();
return ft;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.cart:
if (session.isUserLoggedIn()) {
startActivity(new Intent(MainActivity.this, CartActivity.class));
} else if (new UserAuthentication(MainActivity.this, session).loginAndSignupDialog()) {
startActivity(new Intent(MainActivity.this, CartActivity.class));
}
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar_menu, menu);
final MenuItem menuItem = menu.findItem(R.id.cart);
MenuItemCompat.setActionView(menuItem, R.layout.cart_badge_layout);
final View actionView = MenuItemCompat.getActionView(menuItem);
cartItemCountDisplay = actionView.findViewById(R.id.cart_badge);
setupBadge();
actionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setupBadge();
onOptionsItemSelected(menuItem);
}
});
return super.onCreateOptionsMenu(menu);
}
private void setupBadge() {
int itemCount = (((AppGlobalContent) getApplicationContext()).getSelectedItemsCount());
if (cartItemCountDisplay != null) {
if (itemCount == 0) {
if (cartItemCountDisplay.getVisibility() != View.GONE) {
cartItemCountDisplay.setVisibility(View.GONE);
}
} else {
cartItemCountDisplay.setText(String.valueOf(Math.min(itemCount, 99)));
if (cartItemCountDisplay.getVisibility() != View.VISIBLE) {
cartItemCountDisplay.setVisibility(View.VISIBLE);
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Please suggest me on this.
This will fix your second problem, when you add fragments to your container they will be add to the stack,
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
}
else {
super.onBackPressed();
}
so when the stack entry count is 1 you have to finish the activity.
For the first problem you have to use "pop back stack" while adding the same fragment again use : getSupportFragmentManager().popBackStack();
I've created a tabbed activity, so many things are already done for me. I followed up a tutorial to, when clicking a drawer item, change to another fragment. Now, I need to, when initializing my app, for my MainFragment to be the default. I actually do not know what's showing up at the moment.
Below's the code of MainActivity that's responsible for handling the fragment change:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
setFragmentTransaction(new MainFragment(), "Dashboard");
break;
case R.id.nav_accounts:
setFragmentTransaction(new AccountFragment(), "Accounts");
break;
case R.id.nav_categories:
break;
case R.id.nav_transactions:
break;
case R.id.nav_reports:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setFragmentTransaction(Fragment fragment, String title) {
setTitle(title);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
I tried setting up a default, but it didn't affect anything.
Add setFragmentTransaction(new MainFragment(), "Dashboard"); to the bottom of onCreate. That should get your main fragment loaded.
You can do like this, you have to load one of your fragment in the onCreate itself so that it can start when app starts.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.nav_view)
NavigationView navigationView;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
// tags used to attach the fragments
public static final String TAG_CHAR = "characters";
public static final String TAG_CO = "comics";
public static final String TAG_EV = "events";
public static final String TAG_AB = "about";
public static String CURRENT_TAG = TAG_CHAR;
// index to identify current nav menu item
public static int navItemIndex = 0;
public Fragment fragment;
private Fragment sendFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
} else {
navItemIndex = 0;
CURRENT_TAG = TAG_CHAR;
loadHomeFragment();
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void loadHomeFragment() {
selectNavMenu();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
} else {
fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
drawer.closeDrawers();
}
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
sendFragment = new CharacterFragment();
break;
case 1:
sendFragment = new ComicFragment();
break;
case 2:
sendFragment = new EventFragment();
break;
case 3:
sendFragment = new AboutFragment();
break;
default:
sendFragment = new CharacterFragment();
}
return sendFragment;
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
super.onBackPressed();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_char:
navItemIndex = 0;
CURRENT_TAG = TAG_CHAR;
break;
case R.id.nav_com:
navItemIndex = 1;
CURRENT_TAG = TAG_CO;
break;
case R.id.nav_ev:
navItemIndex = 2;
CURRENT_TAG = TAG_EV;
break;
case R.id.nav_about_us:
navItemIndex = 3;
CURRENT_TAG = TAG_AB;
break;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "myFragmentName", fragment);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
}
}
Actually i'm designing one app now.
Slide menu control, this menu have 5 categories like 5 fragments.
Each fragment have different different datas.I implemented slide menu also working perfectly.
Here first fragment is home fragment,In that i need to use tab swipe view control i mean two tabs will be there like tab names recent and all tabs.
So when i press recent tab needs to show something and when i press all tab needs to show something.
But here i don't know how to use i researched for lot but i didn't get those.
What i exactly need is in slide menu home fragment i need tab based fragment
For your reference this screen shot
I need those codes please.And let me know is it possible or not.
Thanks in advance
this is my home fragment
public class HomeFragment extends Fragment {
View view;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new MoviesFragment(), "ONE");
adapter.addFragment(new PhotosFragment(), "TWO");
adapter.addFragment(new SettingsFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
These Fragments are for tab
adapter.addFragment(new MoviesFragment(), "ONE");
adapter.addFragment(new PhotosFragment(), "TWO");
adapter.addFragment(new SettingsFragment(), "THREE");
all are just empty fragments..thanks in advance
this is my main activity
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private Toolbar toolbar;
private FloatingActionButton fab;
// urls to load navigation header background image
// and profile image
private static final String urlNavHeaderBg = "http://api.androidhive.info/images/nav-menu-header-bg.jpg";
private static final String urlProfileImg = "https://lh3.googleusercontent.com/eCtE_G34M9ygdkmOpYvCag1vBARCmZwnVS6rS5t4JLzJ6QgQSBquM0nuTsCpLhYbKljoyS-txg";
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
private static final String TAG_HOME = "home";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// 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();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// name, website
txtName.setText("Ravi Tamada");
txtWebsite.setText("www.androidhive.info");
// loading header background image
Glide.with(this).load(urlNavHeaderBg)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavHeaderBg);
// Loading profile image
Glide.with(this).load(urlProfileImg)
.crossFade()
.thumbnail(0.5f)
.bitmapTransform(new CircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfile);
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
toggleFab();
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
case 2:
// movies fragment
MoviesFragment moviesFragment = new MoviesFragment();
return moviesFragment;
case 3:
// notifications fragment
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 4:
// settings fragment
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//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) {
//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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
//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);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#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
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// show menu only when home fragment is selected
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
// when fragment is notifications, load the menu created for notifications
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, 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(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
// user is in notifications fragment
// and selected 'Mark all as Read'
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
}
// user is in notifications fragment
// and selected 'Clear All'
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
This question already has answers here:
OnClickListener not responding
(2 answers)
RecyclerView inside DrawerLayout within LinearLayout not scrollable/clickable
(1 answer)
Closed 5 years ago.
I'm using MaterialTabHost and NavigationView when i click on navigation drawer item but not working
NavigationView im using example code
Anyone help me fix
My code here
[enter image description here][1]
I think i wrong in function replace frament
MainActivity.java
public class MainActivity extends ActionBarActivity implements MaterialTabListener {
private String TAG = MainActivity.class.getSimpleName();
MaterialTabHost tabHost;
ViewPager pager;
ViewPagerAdapter adapter;
private String[] tabs = {"Home","Category","Favourite"};
Toolbar toolbar;
String strMessage;
private AdView mAdView;
private InterstitialAd mInterstitial;
private String name, link;
private ProgressDialog pDialog;
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private FloatingActionButton fab;
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
private static final String TAG_HOME = "home";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// 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) this.findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
this.setSupportActionBar(toolbar);
tabHost = (MaterialTabHost) this.findViewById(R.id.tabHost);
pager = (ViewPager) this.findViewById(R.id.pager );
adapter = new ViewPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
tabHost.setSelectedNavigationItem(position);
}
});
for(String tab_name:tabs)
{
tabHost.addTab(
tabHost.newTab()
.setText(tab_name)
.setTabListener(MainActivity.this)
);
}
//navigation
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
//end navigation
}
//navigation
private void loadNavHeader() {
// name, website
txtName.setText("Ravi Tamada");
txtWebsite.setText("www.androidhive.info");
// loading header background image
Glide.with(this).load(urlNavHeaderBg)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavHeaderBg);
// Loading profile image
Glide.with(this).load(urlProfileImg)
.crossFade()
.thumbnail(0.5f)
.bitmapTransform(new CircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfile);
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
private void setUpNavigationView() {
//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) {
//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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, HomeFragment.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, HomeFragment.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
//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);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#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
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.ad_linear, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
case 2:
// movies fragment
CategoryFragment moviesFragment = new CategoryFragment();
return moviesFragment;
case 3:
// notifications fragment
CategoryFragment notificationsFragment = new CategoryFragment();
return notificationsFragment;
case 4:
// settings fragment
CategoryFragment settingsFragment = new CategoryFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
//end navigation
#Override
public void onTabSelected(MaterialTab tab) {
// TODO Auto-generated method stub
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(MaterialTab tab) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(MaterialTab tab) {
// TODO Auto-generated method stub
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int num) {
switch (num) {
case 0:
return new HomeFragmentCheck();
case 1:
return new CategoryFragmentCheck();
case 2:
return new FavouriteFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.about:
Intent intab=new Intent(MainActivity.this,AboutActivity.class);
startActivity(intab);
break;
case R.id.update:
showPU();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/m_tab_clr"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<it.neokree.materialtabs.MaterialTabHost
android:id="#+id/tabHost"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_below="#+id/toolbar"
app:accentColor="#color/m_tab_select_accent_clr"
app:primaryColor="#color/m_tab_clr" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/ad_linear"
android:layout_below="#+id/tabHost" />
<LinearLayout
android:id="#+id/ad_linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.app.apk.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/AppTheme.AppBarOverlay">
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"></FrameLayout>
</android.support.design.widget.CoordinatorLayout>