Navigation drawer on ImageView click fails with a NullPointerException - android

I want my navigation drawer to open on an ImageView click, because I disabled the appbar, but it crashes my app when I click on the image. I get a NullPointerException error, but I do not know why... :/
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null
object reference at
lt.test.test.HomeActivity$3.onClick(HomeActivity.java:85)
Line 85:
mDrawerLayout.openDrawer(GravityCompat.START);
HomeActivity.java, is where I want the navigation drawer to open:
public class HomeActivity extends NavigationActivity {
DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ImageView icnMenu = findViewById(R.id.icon_menu);
icnMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START); //error, line 85
}
});
}
}
NavigationActivity.java
public class NavigationActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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();
}
}
#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;
}
}
activity_navigation.xml
<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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/activity_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_navigation"
app:menu="#menu/activity_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>

The problem is that your mDrawerLayout is set to null here:
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
This happens as your layout R.layout.activity_home doesn't contain it.
Perhaps you can just do the following:
setContentView(R.layout.activity_navigation);

It's giving you NPE because you're using different content view
setContentView(R.layout.activity_home);
and your drawer is in activity_navigation.xml
You need to include your variable from parent activity. Don't create new variable. Make variables from parent activity public to access them. And don't initialize drawer three times in NavActivity
public class HomeActivity extends NavigationActivity {
//DrawerLayout mDrawerLayout; don't create this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ImageView icnMenu = findViewById(R.id.icon_menu);
icnMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START); //use drawer from parent activity
}
});
}

Related

How to add icon of NavigationView drawer Android

I am a new application developer. I did an example of (NavigationView drawer) and it works great.But my problem is I need to know how I can add it.
Like this:
I have add it as ImageButton in activity bar_main but I don't need it like that.
As such, I have problems like the following:
I have seen many examples that the icon is not added in this way that is not an ImageButton. It's like come from the system without any ImageButton .So I need do that.
Now if I work like that , it will get overlapped with the search icon.When pressing the search button, the drawer icon should disappear.
my code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
static ImageButton menuRight;
private DrawerLayout drawer;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_m);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
toolbar =findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
menuRight =(ImageButton) findViewById(R.id.leftRight);
menuRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawer.closeDrawers();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_home) {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
} else if (id == R.id.nav_Politics) {
Intent i = new Intent(this, Ploysity.class);
startActivity(i);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
return false;
}
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
super.onBackPressed();
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"></androidx.appcompat.widget.Toolbar>
<ImageButton
android:id="#+id/leftRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:src="#drawable/ic_menu_black_24dp" />
</RelativeLayout>
</com.google.android.material.appbar.AppBarLayout>
You can implement left navigation something like this:
<androidx.drawerlayout.widget.DrawerLayout ...>
<!--Main content-->
<androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<!--Left navigation-->
<com.google.android.material.navigation.NavigationView
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_view_menu"
... />
</androidx.drawerlayout.widget.DrawerLayout>
For more information: Material-Design-Navigation-View
if you wish to change the icon, then you need to add this line:
drawer.setHomeAsUpIndicator(R.drawable.ic_your_drawer_icon); //set your own
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(false);
toggle.setHomeAsUpIndicator(R.drawable.ic_custom_drawer_icon);

Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference IN MainActivity.NavigationItemSelected [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am creating Navigation drawer activity .I have added one fragment Camera.
When I click in Profile fragment, I got error
" Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference" in this line. MainActivity.onNavigationItemSelected (MainActivity.java:104).
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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.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 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();
Fragment fragment = null;
Class fragmentClass= null;
if (id == R.id.nav_camera) {
fragmentClass = Camera.class;
// 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) {
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
activitymain.xml
<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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
Your Fragment is null, and you are trying to replace that. try
In your Fragment class add this
public static MyFragment newInstance() {
MyFragment myFragment = new MyFragment();
return myFragment;
}
Then do this in your main activity:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frameLayout,
MyFragment.newInstance()).commit();
// 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;
}

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) {
}
}

Button on ToolBar won't open the Navigation Drawer

I have created a Base Activity that contains a navigation drawer.
The drawer will open on slide, but never through the navigation button on the toolbar. I've been stuck on this for quite a while, and I had it working prior to creating this base class and I don't think I've changed anything logically.
I know this question has been asked before, but I've gone through all other similar posts and have not been able to solve it.
Thanks in advance!
public class DrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private Toolbar toolbar;
private NavigationView navigationView;
private boolean enableToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enableToolbar = true;
}
#Override
public void setContentView(int layoutResID){
super.setContentView(R.layout.activity_drawer);
setToolbar();
setDrawerLayout();
setNavigationDrawer();
setToolbarOnClickListener();
if(!useToolbar())
toolbar.setVisibility(View.GONE);
inflateToContentFrame(layoutResID);
}
public void setUsesToolbar(boolean _enable){
enableToolbar = _enable;
}
private boolean useToolbar(){
return enableToolbar;
}
private void setToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setDrawerLayout(){
drawerLayout = (DrawerLayout)getLayoutInflater().inflate(R.layout.activity_drawer, null);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
DrawerActivity.this.invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
DrawerActivity.this.invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
DrawerActivity.this.toolbar.setAlpha(1 - slideOffset / 2);
}
};
toggle.setDrawerIndicatorEnabled(true);
drawerLayout.addDrawerListener(toggle);
drawerLayout.post(new Runnable() {
#Override
public void run() {
toggle.syncState();
}
});
}
private void setNavigationDrawer(){
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void setToolbarOnClickListener(){
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DrawerActivity.this.drawerLayout.openDrawer(GravityCompat.START);
}
});
}
private void inflateToContentFrame(int layoutResID){
FrameLayout content = (FrameLayout) findViewById(R.id.content_frame);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(layoutResID, content, true);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.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.drawer, 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) {
int id = item.getItemId();
Intent _intent;
if (id == R.id.nav_classes) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_appointments) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_clients) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_payments) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if(id == R.id.nav_Settings){
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_share) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_send) {
_intent = new Intent(this, AppointmentsActivity.class);
}else{
_intent = new Intent(this, AppointmentsActivity.class);
}
drawerLayout.closeDrawer(GravityCompat.START);
startActivity(_intent);
return true;
}
}
XML:
<?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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<include
layout="#layout/app_bar_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_drawer"
app:menu="#menu/activity_drawer_drawer"
/>
</android.support.v4.widget.DrawerLayout>
The DrawerLayout instance you're setting up the Toggle with is not the instance that's on-screen. In the setDrawerLayout() method, you're inflating a new layout that's never used.
Instead of inflating there, use findViewById() to get the DrawerLayout instance that's created and added to the Activity in the super.setContentView() call.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
Also, you can omit the toolbar.setNavigationOnClickListener() call, as the ActionBarDrawerToggle will set a listener itself, and handle opening and closing the drawer internally.

Navigation Drawer stops working after implementing MaterialSearchView

My main activity consists of a navigation drawer and switching between fragments was working fine. Now i tried to implement Material Searchview using this library which requires the toolbar to be set last inside the xml file. So now my serachview is working fine but onNavigationItemSelected stops working and i cant switch between fragments. If inside the xml i write navigation drawer below the toolbar navigation starts working again but searchview stops working. Please help me.
activity_home.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
<com.miguelcatalan.materialsearchview.MaterialSearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
HomeActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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);
exploreFragment();
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setVoiceSearch(false);
searchView.setCursorDrawable(R.drawable.custom_cursor);
searchView.setEllipsize(true);
// searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(HomeActivity.this,query,Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Do some magic
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
exploreFragment();
} else if (id == R.id.nav_gallery) {
newFragment();
} 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 exploreFragment(){
fragment = new ExploreFragment();
Bundle bundle = new Bundle();
// bundle.putString("loginToken",loginToken);
// bundle.putString("userId", userId);
fragment.setArguments(bundle);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
}
public void newFragment(){
fragment = new NewFragment();
Bundle bundle = new Bundle();
// bundle.putString("loginToken",loginToken);
// bundle.putString("userId", userId);
fragment.setArguments(bundle);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
}
I think you forgot to add actionviewclass
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="com.miguelcatalan.materialsearchview.MaterialSearchView" />

Categories

Resources