Hello i am new to android. I want the navigation drawer scroll to bottom on an item click. Is it possible?
if (id == R.id.setting){
--CODE--
}
Here if setting is selected i want the navigation drawer to scroll down to bottom. How can it do it? please help.
If I understood it correctly, id.settings is a button, to add the functionality when a user clicks a button you should use this code:
Button settingsBtn = (Button) findViewById(R.id.settings);
settingsBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
--CODE--
}
});
You can use onNavigationItemSelected() to handle NavigationDrawer items.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.setting: {
// do something when clicked
break;
}
}
//close navigation drawer
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
And add implements NavigationView.OnNavigationItemSelectedListener to your Activity :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
Remember to initialize and set the listener in onCreate():
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Related
I have two activities,one is a MainActivity which has navigation drawer working.The Other is a testActivity which extends from the MainActivity.When I move from the MainActivity to the testActivity the navigation bar appears there but not working when i click there.
I have read too many posts on this like extending navigation drawer activity to other activities but I didnt understand them.
The following is my MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
Button nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl = (DrawerLayout) findViewById(R.id.activity_main);
t = new ActionBarDrawerToggle(this, dl, R.string.Open, R.string.Close);
nextBtn = (Button)findViewById(R.id.nextAct);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,TestActivity.class);
startActivity(intent);
}
});
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = (NavigationView) findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.account:
Toast.makeText(MainActivity.this, "My Account", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(MainActivity.this, "Settings", Toast.LENGTH_SHORT).show();
break;
case R.id.mycart:
Toast.makeText(MainActivity.this, "My Cart", Toast.LENGTH_SHORT).show();
break;
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
The following is the testActivity.
public class TestActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
The second activity gets the navigation bar as i have extended this from the MainActivity but that is not clickable in this new activity.Can any edit the code so that it will be clickable.
I think that the best way to do this is to use fragments. The navigation drawer + bar stays the same, and you change fragments in the rest of the screen. Hope it helps !
I need set back icon in my toolbar. I created my toolbar using android.support.v7.widget.Toolbar and for back using this code first set onClick to my back icon by this code:
ImageView backIcon = findViewById(R.id.back_icon);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(CreateNewItem.this,MainActivity.class);
startActivity(intent);
finish();
}
});
and add this code:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
it's work and back to activity but my problem it's when using back icon and back to activity see recyclerView is empty and activity not have data. what is my problem?
If You are using Toolbar then no need to set custom back icon, you have to just override this method
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
}
return (super.onOptionsItemSelected(menuItem));
}
and enable Toolbar:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Happy coding!!
I have been working on this nav drawer with activites. I have a couple of activites in my projects that i want to switch between using the nav drawer.
So far I have achieved this
Create Nav drawer and Write some activities code.
Show same nav drawer in all activities.
Start a default activity when app starts.
But now my issue is that when i open my app for first time, it loads my desired activity and i can see this nav drawer. when i switch activity and press the back button, I'm getting this blank activity with nav drawer. I know its some kinda beginner level issue. But please if someone can suggest the edit. Here is my code.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
DrawerLayout drawer;
FrameLayout frameLayout;
private static boolean isLaunch = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.contant_frame);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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, "", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (isLaunch) {
isLaunch = false;
startActivity(new Intent (this,MyAct.class));
}
}
#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;
}
#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_manage) {
startActivity(new Intent(this,About.class));
} else if (id == R.id.nav_share) {
startActivity(new Intent(this,About.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I ve this same app working perfect in simple listview type nav drawer. but now i m trying to implement fancy material design.
Try overriding the onBackButtonPressed method.
Clearing/removing the onBackpressed method in MyAct and About class will bring back the last view with anything that was populated.
But if you want to open some other view or want to start new activity when back key is pressed, you can add your code here in this onBackPressed method
Hope it helps. Cheers!
In my app, I used navigation drawer. Here I listed all the items.
From the image,the items are,
Home
Filter & Sort
WishList
Shop
MyOrder
Settings
LogOut
If I am in the Fragment of Shop , I need to hide it. How to do this?
Please help me.
You can handle it in fragments onAttach method. Set the visibility of perticular item according to your need.
#Override
public void onAttach(Context context) {
super.onAttach(context);
YourActivity activity = (YourActivity)context;
NavigationView navigationView = (NavigationView) activity.findViewById(R.id.yournavigationviewid);
navigationView.getMenu().findItem(R.id.youritemid).setVisible(false);
}
inside your setNavigationItemSelectedListener where you get the selected menuItem, you can implement the code. Also you require to store the instance of the hidden menu item to make it visible later
MenuItem prevMenuItem;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if(prevMenuItem != null) prevMenuItem.setVisible(true) //making visible the previously hidden item.
menuItem.setVisible(false);
prevMenuItem = menuItem //storing the instance of currently hidden item to make it visible later.
return true;
}
});
In your public onNavigationItemSelected(MenuItem item) if you are setting one fragment then automatically drawer will hide. I'm doing like this :
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
toolbar.setTitle(item.toString());
int id = item.getItemId();
if (id == R.id.dashboard) {
fragment = new DashboardFragment();
} else if (id == R.id.manage_users) {
}else{
}
setFragmentLayout(fragment);
return true;
}
Set your fragment according to your requirements.
You can hide the drawer using mDrawerLayout.closeDrawers() in onNavigationItemSelected Listener like this:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_shop:
//do your stuffs or attach fragment
mDrawerLayout.closeDrawers();
return true;
default:
return true;
}
}
}
on the fragments overide the onAttach method. Set the visibility of for items your don't need.
#Override
public void onAttach(Context context) {
super.onAttach(context);
MainActivity activity = (MainActivity)context;
NavigationView navigationView = (NavigationView) activity.findViewById(R.id.navmenu);
// hide the menu items not related to this fragment
Menu m = navigationView.getMenu();
m.findItem(R.id.first).setVisible(false);
m.findItem(R.id.second).setVisible(false);
m.findItem(R.id.therd).setVisible(false);
//and so on
}
I have created MainActivity with NavigationView. When Activity is opened I want to automatically select the first item in the navigation drawer and open Fragment under that item. I've searched a lot but didn't find any proper solutions.
What is the proper way to do this ?
Main Activity:
public class MainActivity extends AppCompatActivity implements Config {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(getResources().getColor(R.color.colorIcons));
if (null != getSupportActionBar())
getSupportActionBar().setLogo(R.drawable.ic_blogger_white);
//Start PostListFragmentWebView
/*PostListFragmentWebView postListFragmentWebView = new PostListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, postListFragmentWebView)
.commit();*/
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigationView);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not set it to checked state.
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was clicked and perform the appropriate action.
switch (menuItem.getItemId()) {
case R.id.posts:
PostListFragmentWebView postListFragment = new PostListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, postListFragment)
.commit();
return true;
case R.id.pages:
PageListFragmentWebView pagetListFragment = new PageListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, pagetListFragment)
.commit();
return true;
case R.id.blog:
BlogInfoFragmentWebView blogInfoFragment = new BlogInfoFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, blogInfoFragment)
.commit();
return true;
default:
Toast.makeText(getApplicationContext(), getResources().getString(R.string.drawer_error), Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we don't want anything to happen so we leave this blank.
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank.
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.getChildAt(0).setSelected(true);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
}
In onCreate(), following code will load the first item's fragment upon first start:
if (savedInstanceState == null) {
navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
}
Thanks to calvinfly for this comment.
Add android:checked="true" to your first menu item.
And manually select one item, using
getSupportFragmentManager().beginTransaction().replace(R.id.frame, postListFragment).commit();
to open fragment.
Instead of normal listener ...
navView.setNavigationItemSelected(new Navigation.View.OnNavigationItemSelectedListener() {bla, bla, bla})
Create the listener as an Obj:
NavigationView.OnNavigationItemSelectedListener navViewListener;
navView.setNavigationItemSelectedListener(navViewListener = new NavigationView.OnNavigationItemSelectedListener() {bla, bla, bla})
...and use the Obj to trigger the listener event:
navViewListener.onNavigationItemSelected(navView.getMenu().getItem(0));
...where getItem(0) is the first menu item.
Use a method getItem(0).setChecked(true) or android:checked="true" at its menu item XML definition.
You could also use navigationView.setCheckedItem(R.id.default)(javadoc) after you setup your navigationview.
just add this code in onCreate method:
FragmentTransaction ftrans = getFragmentManager().beginTransaction();
ftrans.replace(R.id.container, <yourfragment>).commit();
Work for me !
This can be done even better while considering orientation and other configuration changes. We could select whatever nav drawer menuitem depending on whether we are coming from a previous state. Check: For the Navigation drawer wielding Activity:-
public static final String SELECTED_NAV_MENU_KEY = "selected_nav_menu_key";
// The selected grid position
private int mSelectedNavMenuIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
...........................................................
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState != null) {
// Recover assets
mSelectedNavMenuIndex = savedInstanceState.getInt(SELECTED_NAV_MENU_KEY);
// Recover menu as selected
MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
toggleNavMenuItemCheck(menuItem);
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
return;
} else {
MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
toggleNavMenuItemCheck(menuItem);
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
}
}
The toggle method that helps uncheck or check the menu item
private void toggleNavMenuItemCheck(MenuItem menuItem) {
if (menuItem.isChecked()){
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
}
This is how I save the state of the selected menu item. Check:-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_explore:
showExploreFragment(null);
mSelectedNavMenuIndex = 0;
break;
case R.id.nav_orders:
mSelectedNavMenuIndex = 1;
break;
case R.id.nav_settings:
mSelectedNavMenuIndex = 2;
break;
default:
showExploreFragment(null);
mSelectedNavMenuIndex = 0;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
// Save any important data for recovery
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_NAV_MENU_KEY, mSelectedNavMenuIndex);
}
NB: The line with code:
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
Can be replaced by the code:
onNavigationItemSelected(menuItem);
in menu.xml remember to mention android:checkable="true" for single item and android:checkableBehavior="single" for a group of items.
<item
android:id="#+id/pos_item_help"
android:checkable="true"
android:title="Help" />
<group
android:id="#+id/group"
android:checkableBehavior="single">
<item
android:id="#+id/menu_nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/menu_nav_home" />
</group>
then inside NavigationItemSelectedListener use setCheckedItem(R.id.item_id_in_menu) to make it selected.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.pos_item_pos:
navigationView.setCheckedItem(R.id.pos_item_pos);
break;
case R.id.pos_item_orders:
navigationView.setCheckedItem(R.id.pos_item_orders);
break;
default:
}
return true;
}
And you do not have to do the dirty task of managing the selected item anymore. navigationView manages it by self.
1.) To land to the HomeFragment initially, use this inside your onCreate() in MainActivity:
Fragment fragment = new HomeFragment();
// replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
2.) To set the item as selected in navigationDrawer set the item as checked in navigation_menu.xml
android:checked = "true"