I'm implementing persistent search view like google play in my android application.here is my code.
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private EditText searchView;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
private TextView appName;
private boolean isNavigationDrawerOpened;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CoordinatorLayout coordinatorLayout = (CoordinatorLayout)findViewById(R.id.mainLayout);
coordinatorLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(isNavigationDrawerOpened){
hideSearchAndEnableAppName();
}
return false;
}
});
searchView = (EditText) findViewById(R.id.searchView);
appName = (TextView) findViewById(R.id.appName);
searchView.setVisibility(View.GONE);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),"asdfasdfasdf",Toast.LENGTH_LONG).show();
return false;
}
});
drawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "asdfasfasdf", Toast.LENGTH_SHORT).show();
}
});
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(NavigationDrawerActivity.this,"yayyy mani got it",Toast.LENGTH_LONG).show();
}
});
appName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isNavigationDrawerOpened) {
searchView.setVisibility(View.VISIBLE);
searchView.requestFocus();
appName.setVisibility(View.GONE);
isNavigationDrawerOpened = true;
animateDrawerIndicator(true);
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(view.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
}
}
});
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void hideSearchAndEnableAppName() {
animateDrawerIndicator(false);
isNavigationDrawerOpened = false;
searchView.setVisibility(View.GONE);
appName.setVisibility(View.VISIBLE);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else if(isNavigationDrawerOpened){
hideSearchAndEnableAppName();
}else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
drawer.openDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(),"asdfasdf",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void animateDrawerIndicator(boolean shouldAnimate) {
ValueAnimator anim;
if(shouldAnimate) {
anim = ValueAnimator.ofFloat(0, 1);
} else {
anim = ValueAnimator.ofFloat(1, 0);
}
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
// You should get the drawer layout and
// toggler from your fragment to make the animation
toggle
.onDrawerSlide(drawer,
slideOffset);
}
});
anim.setInterpolator(new DecelerateInterpolator());
anim.setDuration(500);
anim.start();
}
}
Here everything is working fine, but when user has clicked on toolbar edittext(as per my code) i'm changing the hamburger icon to back button. Now if user clicks on back button, it should animate back to hamburger and edittext should be hidden(as per my requirement)
But, for that to happen i need to handle hamburger click. I have tried onClickListners on toggle,actionbartoggle etc.But in vain please help.
When both toolbar and drawer were present.
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
mDrawerToggle.setHomeAsUpIndicator(R.drawable.menu); //set your own
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawer(GravityCompat.START);
}else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
});
This is I used in my app when Change the hamburger icon with other
when set icon than on click of that is not working because
we need to use:
mDrawerToggle.setDrawerIndicatorEnabled(false);
But when only toolbar(No Navigation Drawer):
toolbar = (Toolbar) findViewById(R.id.toolbar);
toggle = new ActionBarDrawerToggle(
this, null, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
mDrawerToggle.setHomeAsUpIndicator(R.drawable.menu); //set your own
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawer(GravityCompat.START);
}else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
});
Then change the hamburger icon to any other as:
toolbar.setNavigationIcon(R.drawable.ic_dehaze_black_24dp);
Directly calling an ActionBarDrawerToggle's onDrawerSlide() method to animate the toggle is messy. A better option is to set a DrawerArrowDrawable as the toggle's Up indicator, and animate that ourselves instead, enabling and disabling the toggle's drawer indicator as necessary.
First, we declare a DrawerArrowDrawable field in the Activity.
private DrawerArrowDrawable searchToggle;
We then initialize it in the onCreate() method, set it as the Up indicator, and define the navigation OnClickListener.
searchToggle = new DrawerArrowDrawable(this);
toggle.setHomeAsUpIndicator(searchToggle);
toggle.setToolbarNavigationClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hideSearchAndEnableAppName();
}
}
);
In the animateDrawerIndicator() method, we first disable the drawer indicator if we're showing the search EditText. This causes the toggle to revert to the Up indicator, which we'll then animate as necessary, switching back to the drawer indicator once the hiding animation is finished.
public void animateDrawerIndicator(final boolean shouldAnimate) {
ValueAnimator anim;
if (shouldAnimate) {
anim = ValueAnimator.ofFloat(0, 1);
// Show the Up indicator instead
// of the drawer indicator
toggle.setDrawerIndicatorEnabled(false);
}
else {
anim = ValueAnimator.ofFloat(1, 0);
}
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
// Animate our Drawable instead of the drawer's
searchToggle.setProgress(slideOffset);
// If we're hiding and have finished,
// re-enable the drawer indicator
if(!shouldAnimate && slideOffset == 0) {
toggle.setDrawerIndicatorEnabled(true);
}
}
});
anim.setInterpolator(new DecelerateInterpolator());
anim.setDuration(500);
anim.start();
}
Related
I made some toolbar animation when I change the navigationViewIcon.
So the animation work only when I back to my main frame, not when I go from main frame to second frame; I made a small record to show it:
I made a small record to show it
I made like this:
private ActionBarDrawerToggle toggle;
mDrawerLayout = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_open, R.string.navigation_close);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.logout: {
logout();
break;
}
}
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
return true;
}
});
//When I change fragment
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
setHomeAsUp(true);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//When I go back to the first fragment
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_menu);
setHomeAsUp(false);
toggle.setDrawerIndicatorEnabled(true);
// Remove the/any drawer toggle listener
toggle.setToolbarNavigationClickListener(null);
protected void setHomeAsUp(boolean isHomeAsUp){
if (this.isHomeAsUp != isHomeAsUp) {
this.isHomeAsUp = isHomeAsUp;
ValueAnimator anim = isHomeAsUp ? ValueAnimator.ofFloat(0, 1) : ValueAnimator.ofFloat(1, 0);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
toggle.onDrawerSlide(mDrawerLayout, slideOffset);
}
});
anim.setInterpolator(new DecelerateInterpolator());
// You can change this duration to more closely match that of the default animation.
anim.setDuration(400);
anim.start();
}
}
and call
setHomeAsUp(boolen)
where boolen was true when I put the back button, false when I put the hamburger menu icon.
Really don't understand this.
I have created an app which uses one activity (Navigation Drawer) and a fragment. But I'm unable to use toolbar back button to navigate back from the fragment to the main activity. Hardware back button works perfectly. I know that I need to override onOptionsItemSelected, catch android.R.id.home, check if there is something in the back stack and then pop it. After changing the fragment, "burger" button changes to "back arrow", but when I click on it the overridden method "onOptionsItemSelected" is never called, rather on click of the back button NavigationDrawer menu opens.
NOTE: I have referred many answers in the StackOverflow including THIS which is the same as that of my problem but that did not work for me. I have been working on this for a week any help is greatly appreciated. Please do not down vote. 1
Here is my code
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void init() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Log.d("Backstack Count", String.valueOf(getSupportFragmentManager().getBackStackEntryCount()));
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
showUpButton(false);
} else {
showUpButton(true);
}
}
});
}
private void showUpButton(boolean show) {
// To keep states of ActionBar and ActionBarDrawerToggle synchronized,
// when you enable on one, you disable on the other.
// And as you may notice, the order for this operation is disabled first, then enable - VERY VERY IMPORTANT.
if (show) {
// Remove hamburger
mDrawerToggle.setDrawerIndicatorEnabled(false);
// Show back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// when DrawerToggle is disabled i.e. setDrawerIndicatorEnabled(false), navigation icon
// clicks are disabled i.e. the UP button will not work.
// We need to add a listener, as in below, so DrawerToggle will forward
// click events to this listener.
} else {
// Show hamburger
mDrawerToggle.setDrawerIndicatorEnabled(true);
invalidateOptionsMenu();
}
// So, one may think "Hmm why not simplify to:
// .....
// getSupportActionBar().setDisplayHomeAsUpEnabled(enable);
// mDrawer.setDrawerIndicatorEnabled(!enable);
// ......
// To re-iterate, the order in which you enable and disable views IS important #dontSimplify.
}
#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) {
// super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// onBackPressed();
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
// return false;
// return super.onOptionsItemSelected(item);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
displayImportFrag();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void displayImportFrag() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Log.d("called", "new frag");
ImportFragment importFragment = new ImportFragment();
ft.add(R.id.fragment_frame, importFragment).addToBackStack(null).commit();
}
}
ImportFragment.java
public class ImportFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.import_fragment, container, false);
return rootView;
}
}
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 problem with the navigation drawer. I want to know how to display recyclerview when the user clicks on different element of each menu.
Here are some source code and an illustrative capture
N.B: different menu items ("Accueil, Contacts Staff, etc ...") are in an .xml file in the layout.
MainActiviy.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setupWindowAnimations();
//définir la toolbr en tant qu'actionbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.setDrawerListener(drawerToggle);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
//on remplit notre viewpager, comme à notre habitude
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return RecyclerViewFragment.newInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
#Override
public int getCount() {
return 1;
}
});
//indique au tablayout quel est le viewpager à écouter
tabLayout.setupWithViewPager(viewPager);
}
private void setupWindowAnimations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Explode explode = new Explode();
getWindow().setExitTransition(explode);
Fade fade = new Fade();
getWindow().setReenterTransition(fade);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#OnClick(R.id.fab)
public void onFabClick() {
Snackbar.make(fab, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).show();
}
}
Sample source code for you
public class NavActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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 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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Hope this helps you
Not understand exactly what you want. Where do you want to display recycler view? You already have OnNavigationItemSelectedListener, just check which menu you have clicked and do what you want:
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.contact:
// do anything you want, ex
showContactList();
break;
}
the function to show your contact list
private void showContactList(){
List<Contact> data = getYourDataSomeHow();
yourAdapter.setData(data);
yourRecyclerView.setAdapter(yourAdapter);
}
I have two fragments in an activity. When fragment A is showing, I want the navigation drawer burger icon to show and the navigation drawer to work. When fragment B is showing, I want the back arrow to show and when it's clicked do an up navigation. However, I can't seem to get the new AppCompat v7 toolbar to show the up arrow at all inside my ActionBarActivity unless the nav drawer is open.
In my activity, for my onCreate() method I have...
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
And then I call mDrawerToggle.syncState(); in my onPostCreate()
I've tried searching on how to programatically trigger the toolbar icon to the back arrow but nothing has worked. From what I've gathered, calling
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
from my fragment should change the icon but that's not the case. This may be a stupid question, but what am I doing wrong?
From what I have seen in the source code of v7 ActionBarDrawerToggle, you can animate the icon to different states without having the drawer being opened.
private enum ActionDrawableState{
BURGER, ARROW
}
private static void toggleActionBarIcon(ActionDrawableState state, final ActionBarDrawerToggle toggle, boolean animate){
if(animate) {
float start = state == ActionDrawableState.BURGER ? 0f : 1.0f;
float end = Math.abs(start - 1);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator offsetAnimator = ValueAnimator.ofFloat(start, end);
offsetAnimator.setDuration(300);
offsetAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
offsetAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float offset = (Float) animation.getAnimatedValue();
toggle.onDrawerSlide(null, offset);
}
});
offsetAnimator.start();
}else{
//do the same with nine-old-androids lib :)
}
}else{
if(state == ActionDrawableState.BURGER){
toggle.onDrawerClosed(null);
}else{
toggle.onDrawerOpened(null);
}
}
}
Morphing between Burger and Arrow depends on values between 0f and 1.0f, basically these are values that the drawer passes to the ActionBarDrawerToggle.
I used ValueAnimator to animate values in this range, i.e mimicking the drawer toggling.
null arguments are safe because ActionBarDrawerToggle does not care at all about drawer views.
Make sure you take a look at new interpolators to do the animation fully-by-the-book of material design guidelines:
fast_out_linear_in
fast_out_slow_in
Another approach is to access mSlider private field of the ActionBarDrawer through reflection and call setPosition(float position) method to toggle between Burger and Arrow.
mSlider is of type (extends) DrawerArrowDrawable.
Personally, I always try to avoid reflection, as long as there is no other way to do your dirty work.
As Support Library updated to 23.0.0, there is a better way to play drawer-arrow animation. So I'm going to improve #Nikola's answer. Here's code:
public static void playDrawerToggleAnim(final DrawerArrowDrawable d) {
float start = d.getProgress();
float end = Math.abs(start - 1);
ValueAnimator offsetAnimator = ValueAnimator.ofFloat(start, end);
offsetAnimator.setDuration(300);
offsetAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
offsetAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float offset = (Float) animation.getAnimatedValue();
d.setProgress(offset);
}
});
offsetAnimator.start();
}
And call it whenever you want by:
playDrawerToggleAnim((DrawerArrowDrawable) toolbar.getNavigationIcon());
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
if (stackHeight > 0) { // if we have something on the stack (doesn't include the current shown fragment)
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
}
});
After ...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getSupportFragmentManager().popBackStack();
return true;
....
}
In my case the icon is animating:
I have used ActionBarDrawerToggle v7.
MainActivity:
Toolbar toolbar = (Toolbar) findViewById(R.id.tool1);
setSupportActionBar(toolbar);
toolbar.setTitle("ToolBar Demo");
toolbar.setLogo(R.drawable.ic_launcher);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
R.string.open_navigation_drawer,
R.string.close_navigation_drawer) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// TODO Auto-generated method stub
super.onDrawerSlide(drawerView, slideOffset);
}
/** Called when a drawer has settled in a completely closed state. */
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("hi");
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) { // <---- added
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) { // <---- added
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState(); // important statetment for drawer to
// identify
// its state
}
#Override
public void onConfigurationChanged(Configuration newConfig) { // <---- added
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.START | Gravity.LEFT)) { // <----
// added
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}