Navigation Menu buttons clickable in Navigation Drawer - android

I've got to this point of creating navigation drawer where I don't know how to make the buttons clickable from the drawer.
My MainActivity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
else{
switch (item.getItemId()){
case R.id.nav_menu:
Toast.makeText(MainActivity.this, "Menu!", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_setings:
Toast.makeText(MainActivity.this, "Settings!", Toast.LENGTH_SHORT).show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
Please note that switch statement in onOptionsItemSelected doesn't work.
My menu xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_menu"
android:title="My Account"/>
<item android:id="#+id/nav_setings"
android:title="Settings"/>
<item android:id="#+id/nav_logout"
android:title="Log Out"/>
</menu>
So, my question is how to make those items from the drawer clickable?

Assuming you also have a NavigationView inside your DrawerLayout, you just have to add an OnNavigationItemSelectedListener:
NavigationView navigation = (NavigationView) findViewById(R.id.navigation);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()) {
case R.id.nav_menu:
// Handle menu click
return true;
case R.id.nav_settings:
// Handle settings click
return true;
case R.id.nav_logout:
// Handle logout click
return true;
default:
return false;
}
}
});

Related

Android: cannot set onCreateOptionsMenu and onOptionsItemSelected in a shared class for NavigationView

I have a NavigationView to place a drawer in an activity and want to use it across multiple activities
Activity:
public class MainActivity extends MenuOptions {
private DemoFragmentCollectionAdapter adapter;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.primaryToolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.cameraIcon:
menuItem.setChecked(true);
Toast.makeText(MainActivity.this, "Camera", Toast.LENGTH_LONG).show();
drawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
}
MenuOptions class:
public class MenuOptions extends AppCompatActivity {
private DrawerLayout drawerLayout;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.settingsIcon:
drawerLayout.openDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_LONG).show();
return true;
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(), "Home icon", Toast.LENGTH_LONG).show();
return true;
default:return super.onOptionsItemSelected(item);
}
}
}
But when I try to tab the home button (which is converted to a drawer menu icon) the app crashes and I get this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
How to solve this issue?

Floating context menu on button click inside Fragment

In my app I have created few buttons in one fragment which will redirect to several activity based on the click. Now if user click button1, they will get a floating context menu conataing the list of the comapny, such as company1, compan2...etc. I have followed this post Opening a floating menu (context menu) in Android? to develop this feature in my app. But the problem is that this code is implemented in Activity, where in my case I want ti implement it in Fragment. I wrote the code but nothig happen with the button click. Now how can I generate this menu on button click
My contextmenu is
<?xml version="1.0" encoding="utf-8"?>
<item android:id="#+id/company_1"
android:title="#string/company_1"></item>
<item android:id="#+id/company_2"
android:title="#string/company_2"></item>
<item android:id="#+id/company_3"
android:title="#string/company_3"></item>
<item android:id="#+id/company_4"
android:title="#string/company_4">
</item>
<item android:id="#+id/company_5"
android:title="#string/company_5"></item>
<item android:id="#+id/company_6"
android:title="#string/company_6">
</item>
My Fragment Class is
public class MainFragment extends Fragment implements View.OnClickListener{
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button button1=(Button) view.findViewById(R.id.button1);
button1.setOnClickListener(this);
registerForContextMenu(button);
Button button2=(Button) view.findViewById(R.id.button2);
button2.setOnClickListener(this);
Button button3=(Button) view.findViewById(R.id.button3);
button3.setOnClickListener(this);
// Inflate the layout for this fragment
return view;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1){
this.getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
setHasOptionsMenu(true);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.company_1:
Toast.makeText(getActivity().getApplicationContext(),"caompany1code",Toast.LENGTH_LONG).show();
return true;
case R.id.company_2:
......
case R.id.company_3:
.....
case R.id.company_4:
....
return true;
case R.id.company_5:
.....
return true;
case R.id.company_6:
.....
return true;
}
return super.onContextItemSelected(item);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Toast.makeText(getActivity(),"My colleagues clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(getActivity(), "News clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(getActivity(), "Navigator clicked", Toast.LENGTH_SHORT).show();
break;
}
}
In MainActivity Class
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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) {
.....
}
Well i found something here :
Try this in your fragment :
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1{getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
}
You are also calling this wrong:
//Instead of button use button1.
registerForContextMenu(button1);
Maybe this will help.
You did use
onCreateOptionsMenu(Menu menu)
in your Activity but you are trying to use
onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
in your fragment.
Use onCreateOptionsMenu(Menu menu) in your fragment as well and set setHasOptionsMenu(true) in your onCreateView method.

onClick event in navigation drawer

I have made a navigation drawer in Android in which I want to implement onClick for it. This is my main activity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle aToggle;
private Toolbar toolbar;
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
private RecyclerView.Adapter adapter;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
aToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.navig, R.string.open, R.string.Close);
navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout.addDrawerListener(aToggle);
toolbar = (Toolbar) findViewById(R.id.nav_action);
toolbar.setNavigationIcon(R.drawable.navig);
setSupportActionBar(toolbar);
aToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setItemIconTintList(null);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerAdapter = new RecyclerAdapter(getApplicationContext());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (aToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}
This is my XML layout for the activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alpit.formula2.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="0dp"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="58dp"
android:orientation="vertical"></android.support.v7.widget.RecyclerView>
<android.support.v7.widget.Toolbar
android:id="#+id/nav_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#EF6C00"
android:orientation="vertical"
android:theme="#style/ThemeOverlay.AppCompat.Dark"></android.support.v7.widget.Toolbar>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFA726"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationTheme">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This is my menu items:
<group
android:id="#+id/gp1"
android:checkableBehavior="single">
<item
android:id="#+id/nav_maths"
android:icon="#drawable/maths"
android:title="Maths" />
<item
android:id="#+id/nav_physics"
android:icon="#drawable/physics"
android:title="Physics" />
<item
android:id="#+id/nav_chem"
android:icon="#drawable/chem"
android:title="Chemistry" />
<item
android:id="#+id/EEE"
android:icon="#drawable/lightbulb"
android:title="Electronics Electrical" />
</group>
<group
android:id="#+id/gp2"
android:checkableBehavior="single">
<item
android:id="#+id/unitconversion"
android:icon="#drawable/unitconversion"
android:title="Unit Conversion" />
<item
android:id="#+id/Scientist"
android:icon="#drawable/scientist"
android:title="Scientist" />
<item
android:id="#+id/favourite"
android:icon="#drawable/favourite"
android:title="Favourite" />
</group>
<group
android:id="#+id/gp3"
android:checkableBehavior="single">
<item
android:id="#+id/Share"
android:icon="#drawable/share"
android:title="Share" />
<item
android:id="#+id/Rate"
android:icon="#drawable/rate"
android:title="Rate" />
<item
android:id="#+id/ads"
android:icon="#drawable/ad"
android:title="Remove Ads" />
<item
android:id="#+id/aboutus"
android:icon="#drawable/aboutus"
android:title="About Us" />
</group>
</menu>
The problem is I am not able to understand how to implement the onClick on the navigation drawer as it is populated by the list given by us not by any listView.
How can I implement onClick on the items of navigation drawer?
You need to add implements NavigationView.OnNavigationItemSelectedListener
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
and add method
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_maths: {
//do somthing
break;
}
}
//close navigation drawer
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
method to set Listener
private void setNavigationViewListener() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
call method in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setNavigationViewListener()
}
Add NavigationItemSelectedListener event to nav_view
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Implement your Activity with NavigationView.OnNavigationItemSelectedListener
and add this code for click 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;
}
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val nav_view: NavigationView = findViewById(R.id.nav_view)
nav_view.setNavigationItemSelectedListener(this)
nav_view.bringToFront();
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.miid_log_out -> Toast.makeText(this, "Working", Toast.LENGTH_SHORT).show()
}
return false
}
}
in your
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (aToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}
add these lines:
switch (item.getItemId()) {
case R.id.nav_maths:
// your logic here.
return true;
case R.id.nav_physics:
//your logic here
return true;
default:
return super.onOptionsItemSelected(item);
}
Below code is for adding toggle to DrawerLayout
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);
And to add listener to Navigation menu items
implements NavigationView.OnNavigationItemSelectedListener
and override below method
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if(id == R.id. nav_maths){
//Handle your stuff here
}
}
Add below code to onCreate method
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Step-1: Extends the NavigationView.OnNavigationItemSelectedListener on your Activity
Step2:
Then there will show an error then override the method:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
return false;
}
get the Id with menuItem.getId() .And Perform Your Action as per your need.
final Step: Add This line in onCreate navigationView.setNavigationItemSelectedListener(this);
That's it.
binding.navigationView.setNavigationItemSelectedListener {
when(it.itemId){
R.id.book -> Toast.makeText(applicationContext, "Booked", Toast.LENGTH_SHORT).show()
}
true
}
fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
}

Navigation drawer, listen to item clicked events

I have this menu layout "navigation_menu.xml":
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"/>
<item
android:id="#+id/item2"
android:title="#string/item2"/>
<item
android:id="#+id/item3"
android:title="#string/item3"/>
</menu>
My main activity layout "activity_main.xml" is this:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And this is the Java code of the main activity where I initialize the drawer:
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer_layout, R
.string.open_drawer, R.string.close_drawer);
drawer_layout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
The drawer opens and closes correctly, but I don't know how to do something when an item is clicked, for example showing a log.
Does anyone know?
Thanks
Use onNavigationItemSelected() method to handle Navigation Drawer Item Click. See Below Code.
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// ...
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);// you need to set Listener.
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// mDrawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.item1: {
}
break;
case R.id.item2: {
}
break;
case R.id.item3: {
}
break;
}
return true;
}

How to select the first item in a navigation drawer and open a fragment on application start

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"

Categories

Resources