Open next activity only after navigation drawer completes it closing animation - android

I'm using Navigation Drawer in my application.
When the user clicks on any of the menu item in drawer, it opens a new Activity (not fragment).
Now, I'm using slide_right_in/slide_left_out animation as transition between activities.
The code works, but these animations conflicts with the closing animation of Navigation Drawer, as even before the drawer gets completely closed, the current activity starts sliding out to left & next activity starts sliding in from right.
So, is there any way to start the animation only after drawer is completely closed?
Thank You

You can open Activity with a delay. For example, in such a way Activity will be started after 250ms:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(<filter>);
startActivity(intent);
finish();
}
}, 250);
mDrawerLayout.closeDrawer(mDrawerList);

I did this somehow similiar to Jan.
Select an item
If an item gets clicked, i save its id and close the Drawer:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
clickedItem = menuItem.getItemId();
drawerLayout.closeDrawers();
return true;
}
});
Listen for drawer close
If the Drawer gets closed i listen for it and check if an item has been clicked. If it has i call my method to handle the navigation click.
drawerToggle = new ActionBarDrawerToggle(activity, drawerLayout, R.string.accessibility_open_nav, R.string.accessibility_open_nav)
{
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
if(clickedItem != 0)
{
handleNavigationClick();
}
}
};
drawerLayout.setDrawerListener(drawerToggle);
Handle the click
Here i react to the item click on open intents in this case (simplified). You need to reset the clickedItem here to 0. That is, because if you go back to an activity, open and close the drawer, it would still have the clickedItem number and would handle the click again.
private void handleItemClick()
{
switch (clickedItem)
{
case R.id.item_1:
do_something_1;
break;
case R.id.item_2:
do_something_2;
break;
}
clickedItem = 0;
}

Every answer is so complicated..... It's so easy.
Just add a drawerlistener and do something in onClosed() method:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
when you select a item from navigation drawer you will call this method to close the drawer:
drawer.closeDrawer(GravityCompat.START);
after the above method call just add below lines and do whatever you want:
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(#NonNull View drawerView) {
}
#Override
public void onDrawerClosed(#NonNull View drawerView) {
startActivity(finalIntent);
// Or else do something here....
}
#Override
public void onDrawerStateChanged(int newState) {
}
});

Don't close navigation drawer. It will slide with the old activity. Or call startActivity after drawerLayout.closeDrawer(drawerList);
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drawerLayout.closeDrawer(drawerList);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
//set animation here
startActivity(intent);
finish();
}

The nikis's answer does not cover all cases. If your Fragment or Activity contains map or CameraView it may costs more time. And differences between simple screen and screen with map too big so it's hard to select a good delay.
The best approach is to send callback to NavigationDrawer from just opened Activity/Fragment in onResume(). Then close drawer in this callback.

I extend all my activities where I want to have a Navigation drawer by DrawerActivity class. Because I had a little animation conflict as well so I start my Activities after Navigation drawer is completely closed. This is implementation which covers all cases:
public class DrawerActivity extends AppCompatActivity {
private String[] mMenuTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mTitle;
private ActionBarDrawerToggle mDrawerToggle;
private Boolean isItemClicked = false;
protected void onCreateDrawer() {
mTitle = getResources().getString(R.string.app_name);
mMenuTitles = new String[]{getString(R.string.drawer_item1), getString(R.string.drawer_item2), getString(R.string.drawer_item3)};
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setScrimColor(getResources().getColor(R.color.black_transparent_30));
// mDrawerLayout.setScrimColor(Color.TRANSPARENT);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mMenuTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
// R.mipmap.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
If item is clicked, I start activity on checked position.
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
if (isItemClicked) {
int position = mDrawerList.getCheckedItemPosition();
startMyActivity(position);
isItemClicked = false;
}
Method setCheckedItem is overriden in extended activities for showing checked item consistently.
setCheckedItem(mDrawerList);
// getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// getSupportActionBar().setTitle(mTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setCheckedItem(ListView mDrawerList) {
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setCheckedItem(mDrawerList);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
mDrawerList.setItemChecked(position, true);
// setTitle(mMenuTitles[position]);
// Toast.makeText(this, mTitle, Toast.LENGTH_SHORT).show();
// startMyActivity(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
public void startMyActivity(int position) {
//is overriden in extended activities for being able to send data to another activity
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
Item is clicked so I set my helper atribute to true.
public void onItemClick(AdapterView parent, View view, int position, long id) {
isItemClicked = true;
selectItem(position);
}
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#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;
}
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}

I have found a simple way to get rid of id you may try this and its working and tested.
OLD ANSWER:
int id = -1;
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
drawer.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
if (id == R.id.NAV_YOUR_ACTIVITY_ONE) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_ONE.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
else if (id == R.id.NAV_YOUR_ACTIVITY_TWO) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_TWO.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
//do not forget to set id again to -1 or else it will cause problem
id=-1;
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
}
UPDATE ANSWER:
You can your ActionBarDrawerToggle too for example observe below code.
int id = -1;
//Use this function for click effect be performed on drawer item clicked
public void perfromDrawerNavigation(){
if (id == R.id.NAV_YOUR_ACTIVITY_ONE) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_ONE.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
else if (id == R.id.NAV_YOUR_ACTIVITY_TWO) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_TWO.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
//do not forget to set id again to -1 or else it will cause problem
id=-1;
}
//you can write this code in onCreate() also
public void initControl(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(
getResources().getString(R.string.activity));
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){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if(id != -1){
perfromDrawerNavigation();
}
}
};
drawer.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
}

Related

Toolbar's up caret opens nav menu

I'm using the v7.widget.Toolbar in my app, but I'm getting some funky functionality. I have my main activity and fragments that are placed over it. When there are no fragments on the backStack, the hamburger button shows and the menu works correctly. When I add a fragment to the backStack, the up caret shows correctly, however when I click the up caret, the nav menu opens instead of the fragment being popped off the stack.
Now if there's a real answer, I'll take it, but at this point I will take a hackish solution. I tried adding a listener so I knew when the action bar button was hit, but that just made it so the fragment popped, the page went back, but the nav menu still opened. onOptionsItemSelected is not being called (due to the way I implemented the Drawer Toggle, but doing it the "correct" way gave me way more problems, such as no nav menu showing on the main page at all).
To sum it up for clarity: The up caret is opening the nav menu, instead of going back.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
setSupportActionBar(toolbar);
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerContent = findViewById(R.id.drawer_content);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new DrawerListItemAdapter(DRAWER_ITEMS, getApplicationContext()));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
Log.d("Main", "Open Menu");
}
};
mDrawerToggle.syncState();
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
ActionBar ab = getSupportActionBar();
if(ab != null){
ab.setDisplayHomeAsUpEnabled(canback);
}
if(!canback){
//App can crash as mDrawerToggle will be null when app launches
try{
mDrawerToggle.syncState();
}catch (Exception e){
e.printStackTrace();
}
}
Log.d("Main", "shouldDisplayHomeUp");
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
Log.d("Main", "Up carat pressed");
getSupportFragmentManager().popBackStack();
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Main", "Menu item clicked: " + Integer.toString(item.getItemId()));
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The solution that worked for me
A combination of Alex' answer (including his comment in the answer) below and this hacky answer.
You can use setToolbarNavigationClickListener() - it sets the listener that handles clicks when drawer indicator is disabled
drawerToggle.setToolbarNavigationClickListener((View view) -> {
getSupportFragmentManager().popBackStack();
});

Cannot catch toolbar home button click event

I've implemented the newest appcompat library and using the Toolbar as action bar. But the problem is I cannot catch the home button / hamburger icon click event. I've tried and looked everything but doesn't seem to find a similar problem.
This is my Activity class :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Set up the drawer.
navDrawerFragment =
(NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
navDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout),
toolbar);
}
And this is my NavigationDrawerFragment class :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
currentSelectedPosition = savedInstanceState.getInt(
STATE_SELECTED_POSITION);
fromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(currentSelectedPosition);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like
// to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
drawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
drawerListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
selectItem(position);
}
});
//mDrawerListView.setAdapter();
//mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return drawerListView;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
fragmentContainerView = getActivity().findViewById(fragmentId);
this.drawerLayout = drawerLayout;
// set a custom shadow that overlays the main
// content when the drawer opens
drawerLayout.setDrawerShadow(
R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view
// with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
drawerToggle = new ActionBarDrawerToggle(
getActivity(),
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// If the user hasn't 'learned' about the drawer,
// open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!userLearnedDrawer && !fromSavedInstanceState) {
drawerLayout.openDrawer(fragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("cek", "item selected");
if (drawerToggle.onOptionsItemSelected(item)) {
Log.d("cek", "home selected");
return true;
}
return super.onOptionsItemSelected(item);
}
when I clicked a menu item, the log "item selected" gets called. But when I click on the home button, it opens navigation drawer but the log "home selected" never get called. I've set onOptionsItemSelected method inside my Activity as well, but it still doesn't get called.
If you want to know when home is clicked is an AppCompatActivity then you should try it like this:
First tell Android you want to use your Toolbar as your ActionBar:
setSupportActionBar(toolbar);
Then set Home to be displayed via setDisplayShowHomeEnabled like this:
getSupportActionBar().setDisplayShowHomeEnabled(true);
Finally listen for click events on android.R.id.home like usual:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
Timber.d("Home pressed");
}
return super.onOptionsItemSelected(menuItem);
}
If you want to know when the navigation button is clicked on a Toolbar in a class other than AppCompatActivity you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar where the the "home" button used to be.
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cek", "home selected");
}
});
If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened and onDrawerClosed so you'll want to see if those callbacks fit your requirements.
mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// event when click home button
}
});
in mycase this code work perfect
This is how I do it to return to the right fragment otherwise if you have several fragments on the same level it would return to the first one if you donĀ“t override the toolbar back button behavior.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
I think the correct solution with support library 21 is the following
// action_bar is def resource of appcompat;
// if you have not provided your own toolbar I mean
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (toolbar != null) {
// change home icon if you wish
toolbar.setLogo(this.getResValues().homeIconDrawable());
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//catch here title and home icon click
}
});
}
I have handled back and Home button in Navigation Drawer like
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
NavigationView navigationView;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
//showing first fragment on Start
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//listener for home
if(id==android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Begin the transaction
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_companies_list) {
fragment = new FirstFragment();
// Handle the action
}
// Begin the transaction
if(fragment!=null){
if(item.isChecked()){
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.WikiCompany, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
drawerToggle.setDrawerIndicatorEnabled(false);
else
drawerToggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
and In each onViewCreated I call
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).updateDrawerIcon();
((HomeActivity) getActivity()).setActionBarTitle("List");
}
This is how I implemented it pre-material design and it seems to still work now I've switched to the new Toolbar. In my case I want to log the user in if they attempt to open the side nav while logged out, (and catch the event so the side nav won't open). In your case you could not return true;.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!isLoggedIn() && item.getItemId() == android.R.id.home) {
login();
return true;
}
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
I changed the DrawerLayout a bit to get the events and be able to consume and event, such as if you want to use the actionToggle as back if you are in detail view:
public class ListenableDrawerLayout extends DrawerLayout {
private OnToggleButtonClickedListener mOnToggleButtonClickedListener;
private boolean mManualCall;
public ListenableDrawerLayout(Context context) {
super(context);
}
public ListenableDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListenableDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets the listener for the toggle button
*
* #param mOnToggleButtonClickedListener
*/
public void setOnToggleButtonClickedListener(OnToggleButtonClickedListener mOnToggleButtonClickedListener) {
this.mOnToggleButtonClickedListener = mOnToggleButtonClickedListener;
}
/**
* Opens the navigation drawer manually from code<br>
* <b>NOTE: </b>Use this function instead of the normal openDrawer method
*
* #param drawerView
*/
public void openDrawerManual(View drawerView) {
mManualCall = true;
openDrawer(drawerView);
}
/**
* Closes the navigation drawer manually from code<br>
* <b>NOTE: </b>Use this function instead of the normal closeDrawer method
*
* #param drawerView
*/
public void closeDrawerManual(View drawerView) {
mManualCall = true;
closeDrawer(drawerView);
}
#Override
public void openDrawer(View drawerView) {
// Check for listener and for not manual open
if (!mManualCall && mOnToggleButtonClickedListener != null) {
// Notify the listener and behave on its reaction
if (mOnToggleButtonClickedListener.toggleOpenDrawer()) {
return;
}
}
// Manual call done
mManualCall = false;
// Let the drawer layout to its stuff
super.openDrawer(drawerView);
}
#Override
public void closeDrawer(View drawerView) {
// Check for listener and for not manual close
if (!mManualCall && mOnToggleButtonClickedListener != null) {
// Notify the listener and behave on its reaction
if (mOnToggleButtonClickedListener.toggleCloseDrawer()) {
return;
}
}
// Manual call done
mManualCall = false;
// Let the drawer layout to its stuff
super.closeDrawer(drawerView);
}
/**
* Interface for toggle button callbacks
*/
public static interface OnToggleButtonClickedListener {
/**
* The ActionBarDrawerToggle has been pressed in order to open the drawer
*
* #return true if we want to consume the event, false if we want the normal behaviour
*/
public boolean toggleOpenDrawer();
/**
* The ActionBarDrawerToggle has been pressed in order to close the drawer
*
* #return true if we want to consume the event, false if we want the normal behaviour
*/
public boolean toggleCloseDrawer();
}
}
The easiest approach we could do is change the home icon to a known icon and compare drawables (because android.R.id.home icon can differ to different api versions
so set a toolbar as actionbar
SetSupportActionBar(_toolbar);
_toolbar.NavigationIcon = your_known_drawable_here;
for (int i = 0; i < _toolbar.ChildCount; i++)
{
View v = _toolbar.GetChildAt(i);
if (v is ImageButton)
{
ImageButton imageButton = v as ImageButton;
if (imageButton.Drawable.GetConstantState().Equals(_bookMarkIcon.GetConstantState()))
{
//here v is the widget that contains the home icon you can add your click events here
}
}
}
In my case I had to put the icon using:
toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
And then listen to click events with default onOptionsItemSelected and android.R.id.home id
For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:
public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
private Activity mActivity;
public NavClickHandler(Activity activity)
{
this.mActivity = activity;
}
public void OnClick(View v)
{
DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
if (drawer.IsDrawerOpen(GravityCompat.Start))
{
drawer.CloseDrawer(GravityCompat.Start);
}
else
{
drawer.OpenDrawer(GravityCompat.Start);
}
}
}
Then, assigned a custom hamburger menu button like this:
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
this.drawerToggle.DrawerIndicatorEnabled = false;
this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);
And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:
this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);
And then you've got a custom menu button, with click events handled.
Try this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
//You can get
}
return super.onOptionsItemSelected(item);
}
Add below code to your onCreate() metod
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
Apart from the answer provided by MrEngineer13, there is also another possible reason why the click event might not have been captured in the onOptionsSelected method. Your DrawerLayout may have overlayed your Toolbar's interface component in the layout XML file. Therefore, whenever you attempt to click the Home button, you're only clicking the DrawerLayout, but not the Home button that's located beneath it.
All you have to do now is rearrange your Toolbar in the corresponding layout XML file so that it is not blocked by any other UI component.
Programmatically, I did attempt to call the bringToFront() method on the toolbar (toolbar.bringToFront()). However, in my app's context, it does not seem to be the solution.

Navigation drawer overlap with fragments in android

I created navigation drawer in my main activity.When i click on navigation drawer item,i am launching fragment in my main activity.if click on navigation drawer icon again,drawer is overlappng with fragment.
i want to detach fragment when i open navigation drawer second time.
Context mContext;
UIController mController;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mPlanetTitles = { "Photos", "Videos", "Settings" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = "test";
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /*
* nav drawer icon to replace 'Up'
* caret
*/
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
selectItem(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
public void selectItem(int position) {
switch (position) {
case 0:
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content,
AlbumListFragment.newInstance()).commit();
break;
}
}
Take a look at remove(android.app.Fragment) or popBackStackImmediate()
I assume you want something like:
...
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mTitle);
//remove the fragment or pop it form the stack when you open the drawer?
getFragmentManager().popBackStackImmediate();
}
...
Hi,The below code will help you
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == android.R.id.home) {
// If the drawer is open, close it; vice versa
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}

NavigationDrawer animation on multiple Activities

I wanted to choose the approach using a navigationDrawer in multiple activities using an AbstractActivity which hosts the NavDrawerl layout and initialization and my inherited activities just set there layout as a content of the drawerLayout. Everything works fine, the Drawer is reachable anywhere. A click on one List item should then start a new activity.
I chose to try this because i don't want one single activity which than hosts 10k lines of code implementing all my inter process communication and background service stuff. Everything works fine. except that the Drawer indeed is closed on my new started activity. this isn't nice because normally if you select something from the list it slides back pretty nice. I wanted to find a compromise and just animate the closing in the new activity which wouldn't make much of a difference. but i can not get it to work because all my calls
public abstract class AbstractNavDrawerActivity extends FragmentActivity {
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.addOnLayoutChangeListener(new OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
}
});
// mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
ViewGroup flContent = (ViewGroup) findViewById(R.id.content);
flContent.addView(getContentView());
ViewGroup leftDrawer = (ViewGroup) findViewById(R.id.left_drawer);
MenuFragment mf = new MenuFragment();
mf.setListener(new DrawerItemClickListener());
getSupportFragmentManager().beginTransaction().add(R.id.left_drawer, mf)
.commitAllowingStateLoss();
}
#Override
protected void onStart() {
super.onStart();
if (getIntent().hasExtra("close")) {
if (getIntent().getExtras().getBoolean("close")) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
protected void onResume() {
super.onResume();
if (getIntent().hasExtra("close")) {
if (getIntent().getExtras().getBoolean("close")) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
}
}
protected abstract View getContentView();
#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);
return true;
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
startActivity(new Intent(this, OneActivity.class));
break;
case 1:
Intent it = new Intent(this, TwoActivity.class);
it.putExtra("close", true);
startActivity(it);
break;
case 2:
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
default:
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class OneActivity extends AbstractNavDrawerActivity {
#Override
protected View getContentView() {
return getLayoutInflater().inflate(R.layout.ac_one, null);
}
does anybody have a clue how we could get this to work looking "cool". I think it would be a nice solution for complex apps. I don't like the One Activity 1943209483280 Fragment Action Listener approach.

Disable item in Navigation Drawer

In my Navigation Drawer I have a problem, when it loads anything in the first spot will crash the app, so my solution to this is to set it to a string that changes to say "(appname) Free" or " (appname) Premium", depending on if the premium upgrade was purchased.
I would like this unclickable as it is currently able to be clicked but nothing happens. Ideally this would be a submenu, or title, but I could not figure out how to implement that. Here is a excerpt of my code:
public class myClass extends SherlockActivity implements
OnItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
mTitle = mDrawerTitle = getTitle();
if (mIsPremium == true) {
mPlanetTitles = getResources().getStringArray(
R.array.planets_array_prem);
} else {
mPlanetTitles = getResources()
.getStringArray(R.array.planets_array);
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
/*
* Toast.makeText( getApplicationContext(),
* "case 0 - A Activity.", Toast.LENGTH_LONG).show(); Intent
* c0 = new Intent(getBaseContext(),
* activity.class); startActivity(c0);
*/break;
case 1:
Toast.makeText(getApplicationContext(),
"case 1 - B Activity", Toast.LENGTH_LONG).show();
Intent c1 = new Intent(getBaseContext(),
ActivityB.class);
startActivity(c1);
break;
default:
}
}
}
public void selectItem(int position) {
switch (position) {
case 0:
// setContentView(R.layout.main);
break;
case 1:
setContentView(R.layout.main);
break;
default:
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
I do not use fragments, I was going to implement the navigation drawer by doing on click and moving to new activities. I am looking for a solution to my primary problem but would welcome any design tips.
Thank you
Edit
With CommonsWare's help I developed this: but nothing is different in my application. I want the first time (case 0 (position 0)) to be disabled.
public class MyArrayAdapter extends ArrayAdapter<String> {
public MyArrayAdapter(Context context, int position) {
super(context, 0);
}
public boolean areAllItemsEnabled() {
return false;
}
public boolean isEnabled(int position) {
if (position == 0) {
return false;
} else {
return true;
}
}
}
As you already know, since you already read the answer, you need to replace your new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles) with a custom Adapter -- perhaps one extending ArrayAdapter<String> -- where you override areAllItemsEnabled() to return false and isEnabled() to return true or false as needed.
See also:
android - disable listview item click and reenable it
Android ListView child View setEnabled() and setClickable() do nothing

Categories

Resources