My app uses a navigation drawer with 2 sections.
Section 1: Character List, Favorites List
Section 2: List of all characters
Character List has the same character selections as section 2 in the navigation drawer. Selecting a character from "Character List" or "Favorites List" in section 1, or from the list in the drawer, will open the character page.
When I am on a character page, I want the back button to bring the user back to the Character List or Favorites List (whichever was last accessed), but never back to a previous Character Page (if it was selected from the navigation drawer).
My Drawer item listener:
public void getDrawerItemClickListener() {
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
int selection = menuItem.getItemId();
String name = menuItem.getTitle().toString();
if(selection == R.id.nav_home) {
Fragment myFragment = new HomeFragment();
replaceFragment(myFragment);
}
if(selection == R.id.nav_fav) {
Fragment myFragment = new FavFragment();
replaceFragment(myFragment);
}
for(int i = 0; i < characters.size(); i++) {
if(characters.get(i).getName().equals(name))
{
Fragment myFragment = new TabFragment();
myFragment.setArguments(createCharacterBundle(characters.get(i)));
replaceFragment(myFragment);
break;
}
}
return false;
}
});
}
My replaceFragment method:
public void replaceFragment(Fragment myFragment) {
FragmentTransaction transaction = mFragmentManager.beginTransaction();
transaction.replace(R.id.containerView, myFragment);
transaction.commit();
}
And my onBackPressed method:
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
mDrawerOpen = true;
}
#Override
public void onDrawerClosed(View drawerView) {
mDrawerOpen = false;
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
public void onBackPressed() {
if (mDrawerOpen) {
mDrawerLayout.closeDrawer(DrawableItemResourceID);
return;
} else {
super.onBackPressed();
}
}
Related
I want my navigation drawer to open the fragment smoothly upon click and close itself without any lag.
Here is the code -
#Override
protected void onCreate(Bundle savedInstanceState) {
navigationView.setNavigationItemSelectedListener(this);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
onNavigationItemSelected(navigationView.getMenu().getItem(0));
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
/* clear backstack of all elements but the last one
* which is the car keys screen
*/
for (int i = 1; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
}
navigationView.getMenu().findItem(R.id.navigation_settings).setVisible(false);
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
}
if (menuItem.getGroupId() == R.id.group_top) {
navigationView.getMenu().setGroupCheckable(R.id.group_bottom, false, true);
navigationView.getMenu().setGroupCheckable(R.id.group_top, true, true);
} else {
navigationView.getMenu().setGroupCheckable(R.id.group_bottom, true, true);
navigationView.getMenu().setGroupCheckable(R.id.group_top, false, true);
}
//Update highlighted item in the navigation menu
menuItem.setChecked(true);
if (fragment != null) {
drawerLayout.closeDrawer(navigationView);
setTitle(menuItem.getTitle());
menuItem.setChecked(true);
fm.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack("fragment")
.commit();
return true;
}
return false;
}
This is in the MainActivity.
Where am I going wrong? Why does it not run smoothly?
Thank you in advance :)
try putting it in a thread with a little delay so it will finish his other commands , like :
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(drawerLayout!=null)
drawerLayout.closeDrawer(navigationView);
}
}, 150);
I have a main activity with navigation drawer and a button to load fragment.
When the main ativity is launched I load the MainFragment.
In this moment all works well. The hamburger icon is showing and my Main fragment was loaded.
Next, I click a button and load a secondFragment. After I load the second fragment, I can use the backbutton and homebutton to come back to main activity without problems.
When I am with second fragment loaded and I make a rotation screen, the back button continues to work well, but the home button disappears and hamburger icon appears.
What am i doing wrong?
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String mSubTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
if (savedInstanceState != null) {
return;
}
MainActivityFragment mainFragment = new MainActivityFragment();
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//transaction.replace(R.id.fragment_container, firstFragment);
transaction.replace(R.id.fragment_container, mainFragment, "princ");
transaction.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Only handle with DrawerToggle if the drawer indicator is enabled.
if (actionBarDrawerToggle.isDrawerIndicatorEnabled() &&
actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
public Fragment getCurrentFragment(){
FragmentManager frgmgr = getSupportFragmentManager();
return frgmgr.findFragmentById(R.id.fragment_container);
}
#Override
public void onBackPressed() {
if (drawerLayout != null) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
}
if ((getCurrentFragment() instanceof MainFragment)) {
finish();
} else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else super.onBackPressed();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
FragmentManager frgmgr = getSupportFragmentManager();
FragmentTransaction transaction = frgmgr.beginTransaction();
Fragment cur_frag;
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
cur_frag = frgmgr.findFragmentById(R.id.fragment_container);
if (!(cur_frag instanceof MainActivityFragment)) {
MainActivityFragment frag = new MainActivityFragment();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.commit();
break;
}
drawerLayout.closeDrawers();
break;
case R.id.logout_drw:
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_email.setText("Agendamento");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mTitle = mDrawerTitle = getTitle();
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (toolbar != null) {
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int i=getSupportFragmentManager().getBackStackEntryCount();
if ((i > 0) || (!(getCurrentFragment() instanceof MainActivityFragment))) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
}
}
}
Main Fragment:
public class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_main, container, false);
Button butCons= (Button) view.findViewById(R.id.butcons);
butCons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SecundaryFrag frag = new SecundaryFragFrag();
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
Secondary Fragment:
public class SecundaryFrag extends Fragment{
public SecundaryFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_consulta_ag, container, false);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
((MainActivity)getActivity()).onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
After Rotation:
Main activty with main fragment:
Before Rotation:
I believe it is related to the fact that the view is recreated after the orientation change. I would take a closer look to the onCreate() from the MainActivity in particular when the
if (savedInstanceState != null) {
return;
}
is triggered.
One option is to retain the fragments and restoring them onCreate. Also you could turn off the recreation by catching the orientation and handle it yourself in the application, you can see here both options explained developer.android.com/guide/topics/resources/
I use MaterialDrawer and code MainActivity is:
public class MainActivity extends AppCompatActivity implements KitchenFragment.CallbackOne {
public static final String TAG = "myLogTag";
private Toolbar mToolbar;
private Drawer drawer;
private FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "CLICK NOCL");
}
});
setSupportActionBar(mToolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content_frame);
if (fragment == null) {
fragment = MenuFragment.newInstance();
fm.beginTransaction()
.add(R.id.content_frame, fragment)
.commit();
}
drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.withHeader(R.layout.drawer_header)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.menu).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.kitchen_title).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.information_title).withEnabled(false)
).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Log.d(TAG, "position clicked: " + position);
Fragment fragment = MenuFragment.newInstance();
switch (position) {
case 1:
fragment = MenuFragment.newInstance();
break;
case 2:
fragment = KitchenFragment.newInstance();
break;
default:
fragment = new Fragment();
}
fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
return false;
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.withOnDrawerNavigationListener(new Drawer.OnDrawerNavigationListener() {
#Override
public boolean onNavigationClickListener(View view) {
Log.d(TAG, "CLICK in DNL");
if (!drawer.getActionBarDrawerToggle().isDrawerIndicatorEnabled()) {
onBackPressed();
return true;
} else
return false;
}
})
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "CLICK OIS");
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState = drawer.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen())
drawer.closeDrawer();
else if (getFragmentManager().getBackStackEntryCount() == 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawer.getActionBarDrawerToggle().syncState();
getFragmentManager().popBackStack();
} else if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
#Override
public void setFirstSelected() {
drawer.setSelection(1);
}
}
I'm trying to trace a Click in mToolbar.setNavigationOnClickListener
and withOnDrawerNavigationListener and onOptionsItemSelected.
None of the listeners not reacted for clicking.
How you see i use Activity that launches Fragment (1), which in turn lets Fragment (2 and 3). In 2 and 3 Fragment in OnCreate i use ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); , and I need to by pressing the back button (in toolbar), returning the previous fragment, and not open Drawer
The MaterialDrawer already handles all the listeners for you. If you need to do an action after the drawer opens or closes you can provide the listener via the DrawerBuilder
For the icon you have this listener:
OnDrawerNavigationListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1158
For drawer close / open this listener:
OnDrawerListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1116
I suggest you to create new Activity using android studio wizard. File->New->Activity->Navigation Drawer Activity.
In that case ActionBarDrawerToaggle is used
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
This toggle contains click listener which handle open/close drawer functionality for you.
Also you can that item clicks implemented through OnNavigationItemSelectedListener.onNavigationItemSelected(MenuItem item)
I'm completely new at Android. I was quite surprised that Android Studio does not have a template for navigation between fragments. I have spent several days now, but still cannot make my code work properly.
I have single activity and two fragments - MainFragment and AboutFragment. About is accessible via drawer menu item. I want to return to MainFragment by pressing back action bar button. The problem is button is not working. Can anyone help me?
Complete minimal Android Studio project:
test.zip
Here is my activity class:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
MainFragment.OnFragmentInteractionListener, AboutFragment.OnFragmentInteractionListener {
private DrawerLayout drawer;
private boolean zOrderSet = false;
private ActionBarDrawerToggle toggleListener;
private FragmentManager.OnBackStackChangedListener mOnBackStackChangedListener =
new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
syncActionBarArrowState();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggleListener = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (!zOrderSet) {
drawer.bringChildToFront(drawerView);
drawer.requestLayout();
drawer.invalidate();
zOrderSet = true;
}
}
public void onDrawerClosed(View view) {
syncActionBarArrowState();
}
public void onDrawerOpened(View drawerView) {
toggleListener.setDrawerIndicatorEnabled(true);
}
};
drawer.setDrawerListener(toggleListener);
toggleListener.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(mOnBackStackChangedListener);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, MainFragment.newInstance("", "")).commit();
}
#Override
protected void onDestroy() {
getSupportFragmentManager().removeOnBackStackChangedListener(mOnBackStackChangedListener);
super.onDestroy();
}
private void syncActionBarArrowState() {
boolean empty = getSupportFragmentManager().getBackStackEntryCount() == 0;
toggleListener.setDrawerIndicatorEnabled(empty);
getSupportActionBar().setDisplayHomeAsUpEnabled(!empty);
}
#Override
public void onBackPressed() {
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) {
if (toggleListener.isDrawerIndicatorEnabled() && toggleListener.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == android.R.id.home && getSupportFragmentManager().popBackStackImmediate()) {
return true;
}
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentTransaction ta = getSupportFragmentManager().beginTransaction();
try {
switch (item.getItemId()) {
case R.id.nav_restart:
ta.replace(R.id.flContent, MainFragment.class.newInstance());
break;
case R.id.nav_about:
ta.replace(R.id.flContent, AboutFragment.class.newInstance()).addToBackStack(null);
break;
default:
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ta.commit();
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
#Override
public void onBackPressed(){
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}
I am using this example for navigation drawer. When clicking on of item of left drawer listview it shows some images but drawerLayout closes not smoothly.
What should I do here for smoothly close left drawer layout after clicking of the item of listview.
Not sure this is the best route, but the way I solved this was to create a pending Runnable that runs in onDrawerClosed. Eg:
private void selectItem(final int position) {
mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
mPendingRunnable = null;
}
}
Works perfect
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
mDrawerLayout.postDelayed(new Runnable() {
#Override
public void run() {
selectItem(position);
}
}, 300);
}
}
Just posting the drawerLayout.closeDrawer() on the message queue using the handler, with a minimal delay solved my problem. Handler.postDelayed() is the key here.
public void selectItem(int position)
{
switch (position)
{
case 0:
DashboardFragment dashboardFragment = new DashboardFragment();
Bundle args = new Bundle();
args.putInt(dashboardFragment.ARG_SCREEN_NUMBER, position);
dashboardFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragmentLayout, dashboardFragment, TAG_DASHBOARD);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
break;
default:
break;
}
// Highlight the selected item, update the title, and close the drawer
drawerList.setItemChecked(position, true);
setTitle(mScreenTitles[position]);
mPendingRunnable = new Runnable()
{
#Override
public void run()
{
drawerLayout.closeDrawer(GravityCompat.START);
}
};
mHandler.postDelayed(mPendingRunnable,50);
}
I don't use threads, because i need to update UI after close the navigation menu.
Following code works for me.
i am using fragment as member variable of class to update ui
setFragment() function use to assign fragment to fragment variable
In onDrawerClosed() event, i update ui.
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
setFragment(position);
}
});
// for getting fragment
protected void setFragment(int p)
{
fragment = null;
switch (position)
{
case 1:
fragment = new DashboardFragment();
break;
}
if (fragment != null)
{
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(p);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
// on close draw , fragment is loaded on screen
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
Please review my MainActivity to make smooth DrawerLayout (open/close) with a custom topBar layout.
public class MainActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment = null;
Class fragmentClass = null;
FrameLayout frameLayout;
TextView topTilte;
DrawerLayout drawer;
NavigationView navigationView;
private boolean isDrawerOpen = false;
#Override
protected void onCreateFinished() {
setContentView(R.layout.activity_main);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
topTilte = findViewById(R.id.toolbar_title);
fragmentClass = HomeFragment.class;
topTilte.setText(R.string.menu_home);
setFragment();
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View view, float slideOffset) {
if(slideOffset > .55 && !isDrawerOpen){
onDrawerOpened(view);
isDrawerOpen = true;
} else if(slideOffset < .45 && isDrawerOpen) {
onDrawerClosed(view);
isDrawerOpen = false;
}
}
#Override
public void onDrawerOpened(#NonNull View view) {
}
#Override
public void onDrawerClosed(#NonNull View view) {
}
#Override
public void onDrawerStateChanged(int i) {
}
});
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void afterInjection() {
}
public void openMenu(View v) {
drawer.openDrawer(Gravity.LEFT);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
topTilte.setText(R.string.menu_home);
fragmentClass = HomeFragment.class;
setFragment();
} else if (id == R.id.nav_profile) {
}
return true;
}
private void setFragment() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}, 200);
}
}