Switching between activities and fragments in navigation drawer - android

I'm not an expert in Android, but really interested in fragments. Would be grateful for your help!
I've implemented a navigation drawer in my app. There is a base drawer activity and a number of fragments a user can switch between from the drawer menu. There is no problem if I want to move to another fragment, but it is working when I use an intent to start a new activity. If you look at my code below you'll see that I use two separate menus: one is for ActionBar icons (cart and search), where intents work perfectly and another one is for Nav drawer to jump between fragments. Is there any way to combine it in one? Basically, I need to move to Profile and Log out activities from nav drawer. Thank you for your advice in advance!
The screen is here
Java file
public class BaseDrawerActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView nvDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_drawer);
drawerLayout = findViewById(R.id.drawer);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
nvDrawer = findViewById(R.id.nvgView);
// Setup drawer view
setupDrawerContent(nvDrawer);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Menu created for cart and search icons
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
//return true;
}
//This method is designed only for cart and search icons
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
} else if (id == R.id.cart) {
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
} else if (id == R.id.search) {
Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
//This method is to set up the drawer content/menu
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) {
// Here we create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_cat:
fragmentClass = CatalogFragment.class;
break;
case R.id.nav_logout:
fragmentClass = CatalogFragment.class;
break;
case R.id.nav_login:
//what should I add here to be able to move to another activity (not a fragment). It doesn't work when I use intents
case R.id.nav_profile:
//need to move to another activity
default:
fragmentClass = HomeFragment.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).addToBackStack("back tag").commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
}

Have you tried doing the same thing you did with the optionItems and preventing the code related to the fragment to be executed when starting an Activity:
public class BaseDrawerActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView nvDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_drawer);
drawerLayout = findViewById(R.id.drawer);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
nvDrawer = findViewById(R.id.nvgView);
// Setup drawer view
setupDrawerContent(nvDrawer);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Menu created for cart and search icons
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
//return true;
}
//This method is design only for cart and search icons
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
} else if (id == R.id.cart) {
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
} else if (id == R.id.search) {
Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
//This method is to set up the drawer content/menu
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) {
// Here we create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_cat:
fragmentClass = CatalogFragment.class;
break;
case R.id.nav_logout:
fragmentClass = CatalogFragment.class;
break;
case R.id.nav_login:
Intent intent = new Intent(getApplicationContext(), OtherActivity.class);
startActivity(intent);
break;
case R.id.nav_profile:
Intent intent = new Intent(getApplicationContext(), ProfileActivity.class);
startActivity(intent);
break;
default:
fragmentClass = HomeFragment.class;
}
//Code related to fragment should not execute when choosing to start an Activity
if(fragmentClass != null){
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).addToBackStack("back tag").commit();
// Highlight the selected item has been done by NavigationView
}
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
}

Related

How to call a fragment every time you open the application?

I have a navigation drawer but the main activity has nothing, only the main page fragment has some thing, I want this fragment to be called every time the application opens. Anyone have any idea how to do this?
here is an example
As in code below, add this line in your code onNavigationItemSelected(nvDrawer.getMenu().getItem(0));
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...From section above...
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
selectDrawerItem(nvDrawer.getMenu().getItem(0));
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}

Fragment to fragment communication within a NavigationDrawer

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

android navigation drawer recreating fragments everytime

I am loading a simple navigation drawer with 3 fragments inside. When i go to 1st fragment and click a button in that fragment then the buttons background color is changed then i am navigating to second fragment and again i am coming back to the 1st fragment i want my fragment (With color changed button) in the backstack. But it is recreated everytime. I have tried multiple ways no luck. Since i am new to fragments i am stuck with this.
public class SampleActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Fragment1.OnFragmentInteractionListener,
Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener {
static Fragment fragment = null;
private static final String FRAGMENT1_TAG = "FRAGMENT1_TAG";
private static final String FRAGMENT2_TAG = "FRAGMENT2_TAG";
private static final String FRAGMENT3_TAG = "FRAGMENT3_TAG";
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
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);
}
#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.dashboard, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
navigateToFragment(id);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public void navigateToFragment(int itemId) {
// Handle navigation view item clicks here.
String FRAGMENT_TAG="";
switch (itemId) {
case R.id.nav_fragment1:
FRAGMENT_TAG = FRAGMENT1_TAG;
fragment = Fragment1.newInstance();
break;
case R.id.nav_fragment2:
FRAGMENT_TAG = FRAGMENT2_TAG;
fragment = Fragment2.newInstance();
break;
case R.id.nav_fragment3:
FRAGMENT_TAG = FRAGMENT3_TAG;
fragment = Fragment3.newInstance();
break;
default:
FRAGMENT_TAG = FRAGMENT1_TAG;
fragment = Fragment1.newInstance();
break;
}
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
Fragment inputFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG);
if (inputFragment == null) {
fragmentTransaction.replace(R.id.content_frame, fragment, FRAGMENT_TAG).addToBackStack(null).commit();
} else {
fragmentTransaction.replace(R.id.content_frame, inputFragment, FRAGMENT_TAG).addToBackStack(null).commit();
}
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
}
}
You should add the code of Fragment2.newInstance(); to know better the behaviour.
This code probably solve your problem:
public class SampleActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Fragment1.OnFragmentInteractionListener,
Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener {
static Fragment fragment1 = null;
static Fragment fragment2 = null;
static Fragment fragment3 = null;
private static final String FRAGMENT1_TAG = "FRAGMENT1_TAG";
private static final String FRAGMENT2_TAG = "FRAGMENT2_TAG";
private static final String FRAGMENT3_TAG = "FRAGMENT3_TAG";
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
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);
}
#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.dashboard, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
navigateToFragment(id);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public void navigateToFragment(int itemId) {
// Handle navigation view item clicks here.
String FRAGMENT_TAG="";
Fragment fragment = null;
switch (itemId) {
case R.id.nav_fragment2:
FRAGMENT_TAG = FRAGMENT2_TAG;
if(fragment2 == null) fragment2 = Fragment2.newInstance();
fragment = fragment2;
break;
case R.id.nav_fragment3:
FRAGMENT_TAG = FRAGMENT3_TAG;
if(fragment3 == null) fragment3 = Fragment3.newInstance();
fragment = fragment3;
break;
default:
FRAGMENT_TAG = FRAGMENT1_TAG;
if(fragment1 == null) fragment1 = Fragment1.newInstance();
fragment = fragment1;
break;
}
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
Fragment inputFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG);
if (inputFragment == null) {
fragmentTransaction.replace(R.id.content_frame, fragment, FRAGMENT_TAG).addToBackStack(null).commit();
} else {
fragmentTransaction.replace(R.id.content_frame, inputFragment, FRAGMENT_TAG).addToBackStack(null).commit();
}
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
}
}
I recommend you to refactor a little bit your code to get a more elegant solution.
Be sure that you're using fragmentTransaction.add() to add a fragment for the first time.
Use stack to keep track on fragment.
Check below link for reference.
https://github.com/rathodchintan/Fragment-Back-Stack
1.do not use replace method if you don't want to reload your fragment.
Instead you it use add method with keeping fragment object in the stack.
if you want to use replace, than check whether fragment is their in the memory by using findFragmentByTag method, and if it's not null use it else create new fragment.

how to get progress circle before loading fragment on click of item in the navigation drawer

I have a navigation drawer in my app.On the click of an item from the navigation drawer particular fragment gets loaded.
but loading of a fragment is taking time of few seconds. i want a progress spinner to display in between so that it does not look like it got stuck.
i tried for using asynchronous task but it did not work because loading fragment from drawer does not include any background process.
Please suggest me something.
Navigation Drawer Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_navigation_fragments);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.test_nav_tool);
setSupportActionBar(toolbar);
SharedPreferences w = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor share = w.edit();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
////if user skip-logout button in nav drawer will disable.
loggedIn=(w.getBoolean("loggedIn", loggedIn));
if(loggedIn==false){
nvDrawer.getMenu().findItem(R.id.logout).setVisible(false);
}
String user_name = (w.getString("name", user));
String type = "b";
type=(w.getString("type", type));
if(user_name.equalsIgnoreCase("name"))
user_name="Guest User";
if(type.equalsIgnoreCase("b")){
nvDrawer.getMenu().findItem(R.id.add_kitchen).setVisible(false);
nvDrawer.getMenu().findItem(R.id.nav_slideshow).setVisible(false);
}
header = LayoutInflater.from(this).inflate(R.layout.test_header_xml, null);
nvDrawer.addHeaderView(header);
TextView tv1=(TextView)header.findViewById(R.id.upload_image);
tv1.setText(user_name);
setupDrawerContent(nvDrawer);
drawerToggle=setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
if (savedInstanceState == null) {
nvDrawer.getMenu().performIdentifierAction(R.id.nav_camera, 0);
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(TestNavigationFragments.this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
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) {
Fragment fragment = null;
setTitle(menuItem.getTitle());
switch(menuItem.getItemId()) {
case R.id.nav_camera:
fragment=new TESTfragNEIBMAP();
break;
case R.id.nav_share:
fragment = new TestFragACCOUNT();
break;
case R.id.nav_send:
fragment = new TESTfragSUPPORT();
break;
case R.id.add_kitchen:
fragment = new TestfragSELLER();
break;
case R.id.nav_slideshow:
fragment=new TestAddKitchenHistory();
break;
case R.id.nav_gallery:
fragment=new TestNavOrder();
break;
case R.id.logout:
try {
SharedPreferences s = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = s.edit();
editor.clear().commit();
Intent intent = new Intent(this, Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
break;
}catch (Exception e){
Intent intent = new Intent(this, Login.class);
startActivity(intent);
}
case R.id.nav_track:
fragment = new TestTrack();
break;
}
if(fragment!=null){
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();
}
}
UPDATE
I have also tried writing progess code in drawer activity and dismiss it in Fragment onViewCreated() method...but i did not see any progress spinner at the time when i click on item of drawer because map is opened and it called its onViewCreated method very fast.
the other option can be adding splash screen on click of item in drawer till map will load but i don't have idea how to do it like how to finish splash screen when the map will become properly visible.
ProgressDialog progress; // Global varibale
// Initiate it in `OnCreateView()`
progress = ProgressDialog.show(getActivity(), "dialog title",
"dialog message", true);
//When Loaded data
progress.dismiss();
i got the issue resolved by closing the drawer before loading the fragments using handler class and set the progress dialog code in onClick of navigation drawer item.

Google Navigation Drawer, handling backpress to set correct checked ite

Currently Used Google Navigation Drawer, having some problem when user backpress.
When user backpress, they didn't update menu Item
Example When I click the App. The sequence are A>B>C>B>C ,if I backpress I wanted to be C>B>A. How should I code this way out ?
My code
public class MainActivity extends AppCompatActivity {
private String appTitle;
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private TextView toolbarTitle;
private Fragment fragment;
private FragmentManager fragmentManager;
private Title title;
private MenuItem menuItem2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setTextColor(Color.parseColor("#FFFFFF"));
setTitle("");
fragmentManager = getSupportFragmentManager();
fragment= new HomeFragment();
title = new Title(getApplicationContext());
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment , title.getStrHome()).commit();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem2 = menuItem;
menuItem.setChecked(true);
drawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_home) {
fragment = new HomeFragment();
appTitle = title.getStrHome();
} else if ((menuItem.getItemId() == R.id.nav_direction)) {
fragment = new DirectionFragment();
appTitle = title.getStrDirection();
} else if ((menuItem.getItemId() == R.id.nav_more)) {
fragment = new MoreFragment();
appTitle = title.getStrMore();
} else if((menuItem.getItemId()==R.id.nav_directory)){
fragment = new DirectoryFragment();
appTitle = title.getStrDirectory();
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
replaceFragment(fragment,appTitle);
return true;
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle
(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
if (fragmentManager.getBackStackEntryCount() > 0 ){
fragmentManager.popBackStack();
toolbarTitle.setText(appTitle);
menuItem2.setChecked(true);
} else {
finish();
}
}
}
public void replaceFragment(Fragment fragment, String tag){
toolbarTitle.setText(tag);
FragmentTransaction ft = fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As stated on the official page on Android tasks and back stack you can see how you can accomplish your desired behaviour using the FLAG_ACTIVITY_CLEAR_TOP in your Intent flags. This picture demonstrates it very well.
Your regular back button proceeds as:
When you specify this flag, you get a behavior like you need
Edit:
The official documentation states:
FLAG_ACTIVITY_CLEAR_TOP
If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the
other activities on top of it are destroyed
This means, there will be no duplicates of your different Activities, and you will have a clean Back Stack.
In your example A>B>C>B>C would not be possible. Instead it would be A>B>C, since B and C already exist in the stack, they will not be added, but replaced instead.
Study the Android Activity Launch Mode.
here is the clear Explanation available.
Just take a look.

Categories

Resources