How to properly combine NavigationView and BottomNavigationView - android

I need to use both elements and this is what I have at the moment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent">
<android.support.v4.widget.DrawerLayout 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">
<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.v4.widget.DrawerLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorAccent"
app:menu="#menu/menu_bottom" />
</RelativeLayout>
My problem here is that the BottomNavigationView is in front of the NavigationView, which should not be the case (I'm talking about the y-index). I also tried using a CoordinatorLayout instead, but then the BottomNavigationView is stuck at the display's top.

I would simply use DrawerLayout as the root element and inside the DrawerLayout you can put a layout for containing the main screen and a NavigationView for the menu. After you can put the BottomNavigationView into the main layout.
<android.support.v4.widget.DrawerLayout 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/maincontent"/>
<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.v4.widget.DrawerLayout>
maincontent.xml
<FrameLayout..>
...
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorAccent"
app:menu="#menu/menu_bottom" />
</FrameLayout>

Here this code runs perfectly for me
nav_header_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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="#dimen/nav_header_height"
android:gravity="bottom"
android:orientation="vertical"
android:background="#drawable/nav_header_background">
<LinearLayout
android:layout_alignParentBottom="true"
android:orientation="vertical"
android:padding="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/nav_header_background">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:civ_border_color="#color/white"
app:civ_border_width="2dp" />
<TextView
android:id="#+id/login_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text=""
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/login_email_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#color/white" />
</LinearLayout>
</RelativeLayout>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
<RelativeLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_nav_view">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="#color/colorAccentDark"
app:itemIconTint="#color/white"
app:itemTextColor="#color/white"
android:foregroundGravity="bottom"
app:menu="#menu/bottom_nav_menu" />
</RelativeLayout>
<com.google.android.material.navigation.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_home"
app:menu="#menu/activity_home_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Now the most important the Java file
HomeActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.login.LoginManager;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.OnConnectionFailedListener {
private FirebaseAuth mAuth;
GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
FirebaseUser user;
TextView name3;
TextView emailid;
CircleImageView circleImageView;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationView navView = findViewById(R.id.bottom_nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header=navigationView.getHeaderView(0);
mAuth = FirebaseAuth.getInstance();
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
user = mAuth.getCurrentUser();
name3=(TextView)header.findViewById(R.id.login_name);
emailid=(TextView)header.findViewById(R.id.login_email_id);
circleImageView=(CircleImageView) header.findViewById(R.id.imageView);
sharedPreferences=getApplicationContext().getSharedPreferences("owl_pref",MODE_PRIVATE);
editor=sharedPreferences.edit();
editor.apply();
if(sharedPreferences.getString("method","").equals("facebook")){
emailid.setText(sharedPreferences.getString("login_mail",""));
name3.setText(sharedPreferences.getString("login_name",""));
String url=sharedPreferences.getString("login_profile_image","");
Glide.with(this).load(url).placeholder(R.drawable.logo).override(124,124).into(circleImageView);
}
if(sharedPreferences.getString("method","").equals("google")){
emailid.setText(sharedPreferences.getString("login_mail",""));
name3.setText(sharedPreferences.getString("login_name",""));
String url=sharedPreferences.getString("login_profile_image","");
Glide.with(this).load(url).placeholder(R.drawable.logo).override(124,124).into(circleImageView);
}
if(sharedPreferences.getString("method","").equals("email")){
emailid.setText(sharedPreferences.getString("login_mail",""));
name3.setText(sharedPreferences.getString("login_name",""));
//String url=sharedPreferences.getString("login_profile_image","");
Glide.with(this).load(R.drawable.logo).override(124,124).into(circleImageView);
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new FragmentHomeActivity()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new FragmentHomeActivity();
break;
case R.id.navigation_dashboard:
fragment = new FragmentDashboardActivity();
break;
case R.id.navigation_star:
fragment = new FragmentRewardActivity();
break;
case R.id.navigation_discuss:
fragment = new FragmentDiscussActivity();
break;
case R.id.navigation_profile:
fragment = new FragmentProfileActivity();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
return true;
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the FragmentHomeActivity/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
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_home) {
Intent intent=new Intent(HomeActivity.this,HomeActivity.class);
startActivity(intent);
showToast("Already in Home Section");
} else if (id == R.id.nav_question_answer) {
Intent intent=new Intent(HomeActivity.this,QuestionActivity.class);
startActivity(intent);
} else if (id == R.id.nav_upload) {
Intent intent=new Intent(HomeActivity.this,UploadActivity.class);
startActivity(intent);
//Animatoo.animateFade(this);
} else if (id == R.id.nav_logout) {
signOut();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void openDrawer() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.openDrawer(GravityCompat.START);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signOut() {
user = mAuth.getCurrentUser();
editor.clear().commit();
if (user != null) {
mAuth.signOut();
Log.d("owl","enter");
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(HomeActivity.this, "Signed Out", Toast.LENGTH_LONG).show();
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
if (AccessToken.getCurrentAccessToken() != null && com.facebook.Profile.getCurrentProfile() != null) {
LoginManager.getInstance().logOut();
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
Now
activity_home_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_question_answer"
android:icon="#drawable/ic_question_answer_black_24dp"
android:title="#string/menu_question_answer" />
<item
android:id="#+id/nav_upload"
android:icon="#drawable/ic_cloud_upload_black_24dp"
android:title="#string/menu_upload" />
<item
android:id="#+id/nav_logout"
android:icon="#drawable/ic_exit_to_app_black_24dp"
android:title="#string/menu_logout" />
</group>
<!--<item android:title="Extras">
<menu>
<item
android:id="#+id/nav_pricing"
android:icon="#drawable/ic_attach_money_black_24dp"
android:title="#string/menu_pricing" />
</menu>
</item>-->
</menu>
bottom_nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home">
</item>
<item
android:id="#+id/navigation_dashboard"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_dashboard">
</item>
<item
android:id="#+id/navigation_star"
android:icon="#drawable/ic_star_black_24dp"
android:title="#string/title_star">
</item>
<item
android:id="#+id/navigation_discuss"
android:icon="#drawable/ic_chat_black_24dp"
android:title="#string/title_discuss">
</item>
<item
android:id="#+id/navigation_profile"
android:icon="#drawable/ic_perm_identity_black_24dp"
android:title="#string/title_profile">
</item>
</menu>
The main thing is in the drawer layout the bottom navigation view is inserted
THE BOTTOM NAVIGATION VIEW IS WORKING WITH THE FRAME LAYOUT IN THE activity_home.xml one activity is holding the Bottom Navigation View

Related

When click on the menu icon to open NavigationDrawer it crashes

When i click on the icon to open the NavigationDrawer my app suddenly crashes and i am trying to solve this about 3 days. Can anyone help me?
I am using Android Studio and this is my first app.
My problem is to open the NavigationDrawer by clicking on the icon on app bar.
Codes:
MainActivity.java
package com.example.chatapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
FirebaseAuth mAuth;
FirebaseUser mUser;
DatabaseReference mUserRef;
String profileImageUriV, usernameV;
CircleImageView profileImageHeader;
TextView usernameHeader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Chat App");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
mAuth=FirebaseAuth.getInstance();
mUser=mAuth.getCurrentUser();
mUserRef= FirebaseDatabase.getInstance().getReference().child("Users");
drawerLayout=findViewById(R.id.drawerLayout);
navigationView=findViewById(R.id.navView);
View view=navigationView.inflateHeaderView(R.layout.drawer_header);
profileImageHeader=view.findViewById(R.id.profileImage_Header);
usernameHeader=view.findViewById(R.id.usernameHeader);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (mUser==null)
{
SendUserToLoginActivity();
}
else{
mUserRef.child(mUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
profileImageUriV=dataSnapshot.child("profileImage").getValue().toString();
usernameV=dataSnapshot.child("username").getValue().toString();
Picasso.get().load(profileImageUriV).into(profileImageHeader);
usernameHeader.setText(usernameV);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "Sorry! Something going wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
private void SendUserToLoginActivity() {
Intent intent=new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
case R.id.profile:
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
break;
case R.id.friend:
Toast.makeText(this, "Friend", Toast.LENGTH_SHORT).show();
break;
case R.id.findFriend:
Toast.makeText(this, "Find Friend", Toast.LENGTH_SHORT).show();
break;
case R.id.chat:
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
break;
case R.id.logout:
Toast.makeText(this, "Logout", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==android.R.id.home){
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return true;
}
}
Drawer_Menu.xml:
<group android:id="#+id/first">
<item android:id="#+id/home"
android:title="Home"
android:icon="#drawable/ic_home"/>
<item android:id="#+id/profile"
android:title="Profile "
android:icon="#drawable/ic_profile"/>
<item android:id="#+id/friend"
android:title="Friend "
android:icon="#drawable/ic_friend"/>
<item android:id="#+id/findFriend"
android:title="Find Friend "
android:icon="#drawable/ic_find_friend"/>
<item android:id="#+id/chat"
android:title="Chat "
android:icon="#drawable/ic_chat"/>
</group>
<group android:id="#+id/second">
<item android:id="#+id/logout"
android:title="Logout "
android:icon="#drawable/ic_logout"/>
</group>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/app_bar"
layout="#layout/main_appbar" />
<EditText
android:id="#+id/inputAddPost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:background="#drawable/input_add_post_bg"
android:hint="Post something here :)"
android:paddingLeft="50dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/app_bar" />
<ImageView
android:id="#+id/addImagePost"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="#+id/inputAddPost"
app:layout_constraintStart_toStartOf="#+id/inputAddPost"
app:layout_constraintTop_toTopOf="#+id/inputAddPost"
app:srcCompat="#drawable/ic_add_post_image" />
<ImageView
android:id="#+id/send_post_imageView"
android:layout_width="53dp"
android:layout_height="48dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="#+id/inputAddPost"
app:layout_constraintEnd_toEndOf="#+id/inputAddPost"
app:layout_constraintTop_toTopOf="#+id/inputAddPost"
app:srcCompat="#drawable/send_post" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inputAddPost"
android:background="#color/colorGray"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
build.gradle:
implementation 'com.google.firebase:firebase-auth:19.3.0'
implementation 'com.google.firebase:firebase-core:17.3.0'
implementation 'com.google.firebase:firebase-storage:19.1.1'
implementation 'com.firebaseui:firebase-ui-database:6.2.1'
implementation 'com.google.android.material:material:1.0.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.squareup.picasso:picasso:2.71828'
I think You would have missed mentioning the id of the DrawerLayout in your 'activity_main.xml' through which our activity finds the Layout in the XML file
android:id="#+id/drawerLayout"
Below is the code after updating.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/app_bar"
layout="#layout/main_appbar" />
<EditText
android:id="#+id/inputAddPost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:background="#drawable/input_add_post_bg"
android:hint="Post something here :)"
android:paddingLeft="50dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/app_bar" />
<ImageView
android:id="#+id/addImagePost"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="#+id/inputAddPost"
app:layout_constraintStart_toStartOf="#+id/inputAddPost"
app:layout_constraintTop_toTopOf="#+id/inputAddPost"
app:srcCompat="#drawable/ic_add_post_image" />
<ImageView
android:id="#+id/send_post_imageView"
android:layout_width="53dp"
android:layout_height="48dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="#+id/inputAddPost"
app:layout_constraintEnd_toEndOf="#+id/inputAddPost"
app:layout_constraintTop_toTopOf="#+id/inputAddPost"
app:srcCompat="#drawable/send_post" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inputAddPost"
android:background="#color/colorGray"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>

Unable to open navigation drawer [duplicate]

In google developer blog post . I read about new way to create navigation drawer using new dependency called
compile 'com.android.support:design:22.2.0'
but I didn’t found exact way to create navigation drawer using this new dependency.
In build.gradle , I have added dependency
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:appcompat-v7:22.0.0'
in layout file added following code (based on google blog post)
<android.support.v4.widget.DrawerLayout
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="match_parent"
android:fitsSystemWindows="true">
<!-- your content layout -->
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
Aslo I tried to extend class using ActionBarActivity but its deprecated?
Ref:http://android-developers.blogspot.in/2015/05/android-design-support-library.html
Any help appreciated .Thank you
Hi try following steps
Add Android design support library dependency
compile 'com.android.support:design:22.2.1'
Create a header for the navigation drawer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#drawable/header"
android:padding="16dp"
android:orientation="vertical"
android:gravity="bottom">
<TextView
android:textColor="#ffffff"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nirav Kalola\nnkDroid"
/>
</LinearLayout>
Create a menu for navigation drawer items
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="nkdroid.tutorial.navigationview.MainActivity">
<group android:checkableBehavior="single">
<item
android:id="#+id/navigation_item_1"
android:icon="#drawable/ic_action_home"
android:title="Home"/>
<item
android:id="#+id/navigation_item_2"
android:icon="#drawable/ic_action_info"
android:title="About Us"/>
<item
android:id="#+id/navigation_subheader"
android:title="Tutorials">
<menu>
<item
android:id="#+id/navigation_sub_item_1"
android:icon="#drawable/ic_image_looks_one"
android:title="Android Tutorials"/>
<item
android:id="#+id/navigation_sub_item_2"
android:icon="#drawable/ic_image_looks_two"
android:title="IOS Tutorials"/>
</menu>
</item>
</group>
</menu>
Create Navigation View with header and items
<android.support.v4.widget.DrawerLayout
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="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true">
<!--Main content-->
<LinearLayout
android:orientation="vertical"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/app_bar"/>
</LinearLayout>
<!--Navigation Drawer-->
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/menu_drawer"/>
</android.support.v4.widget.DrawerLayout>
Implementing Navigation View
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private Toolbar toolbar;
private NavigationView mDrawer;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private int mSelectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setToolbar();
initView();
drawerToggle=new ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
mDrawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
//default it set first item as selected
mSelectedId=savedInstanceState ==null ? R.id.navigation_item_1: savedInstanceState.getInt("SELECTED_ID");
itemSelection(mSelectedId);
}
private void setToolbar() {
toolbar= (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
}
private void initView() {
mDrawer= (NavigationView) findViewById(R.id.main_drawer);
mDrawer.setNavigationItemSelectedListener(this);
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout);
}
private void itemSelection(int mSelectedId) {
switch(mSelectedId){
case R.id.navigation_item_1:
mDrawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.navigation_item_2:
mDrawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.navigation_sub_item_1:
mDrawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.navigation_sub_item_2:
mDrawerLayout.closeDrawer(GravityCompat.START);
break;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mSelectedId=menuItem.getItemId();
itemSelection(mSelectedId);
return true;
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
//save selected item so it will remains same even after orientation change
outState.putInt("SELECTED_ID",mSelectedId);
}
}
you can directly download source code from my blog
hello #user3739665 i am also trying to lean support library, but i don't think there is proper way(because no sample available right now). so here is my tried code, just for demonstration how to use that lib.
i change that layout to like below added main fragment, you can also add toolbar.
<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:fitsSystemWindows="true"
android:layout_height="match_parent">
<!-- your content layout -->
<!--<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<include layout="#layout/about_fragment"></include>
<android.support.design.widget.NavigationView
android:id="#+id/nav_draw"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer" />
i have create drawer.xml for menu and drawer_header.xml for user detail just like show in blog
my activity code
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
View root;
NavigationView nav_draw;
DrawerLayout drawer_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
root = getLayoutInflater().inflate(R.layout.activity_main, null);
setContentView(root);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
nav_draw = (NavigationView) findViewById(R.id.nav_draw);
nav_draw.setNavigationItemSelectedListener(this);
/* getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AboutPagerFragment())
.commit();*/
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawer_layout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.navigation_item_1) {
Snackbar
.make(root, "First item Selected", Snackbar.LENGTH_LONG)
//.setAction(R.string.snackbar_action, myOnClickListener)
.show();
}
menuItem.setChecked(true);
drawer_layout.closeDrawers();
return false;
}
/*#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;
}*/
}
add this in you build.gradle
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:support-v4:22.2.0'
}
drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/navigation_item_1"
android:checked="true"
android:title="#string/navigation_item_1">
</item>
<item
android:id="#+id/navigation_item_2"
android:title="#string/navigation_item_2" />
<item
android:id="#+id/navigation_subheader"
android:title="#string/navigation_subheader">
<menu>
<item
android:id="#+id/navigation_sub_item_1"
android:title="#string/navigation_sub_item_1" />
<item
android:id="#+id/navigation_sub_item_2"
android:title="#string/navigation_sub_item_2" />
</menu>
</item>
</group>
</menu>
drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:gravity="center"
android:layout_height="130dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView" />
</LinearLayout>
EDIT
added navigation item open,close, enable items selection
The "java part" can look like this:
Set your activity as a listener
navView.setNavigationItemSelectedListener(this);
And than handle events the same way you handle menu interaction
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
if (id == R.id.some_item_1) {
} else if (id == R.id.some_item_2) {
} else {
throw new IllegalStateException("Unsupported menu item");
}
return true;
}
Check this github project for all examples of using design library.
Tutorial: Navigation View Design Support Library
<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"
android:fitsSystemWindows="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
...
/>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
activity_main
<?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">
<include
layout="#layout/app_bar_main"
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" />
</android.support.v4.widget.DrawerLayout>
app_bar_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.azim.innovation.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.azim.innovation.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
nav_header_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
activity_main_drawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="Import" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="Gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="Slideshow" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_manage"
android:title="Tools" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="Share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
</menu>
colors
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
dimens
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="nav_header_vertical_spacing">16dp</dimen>
<dimen name="nav_header_height">160dp</dimen>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>
MainActivity
package com.azim.innovation;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawer;
#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);
if (fab != null)
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();
}
});
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
}
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.START)) {
mDrawer.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();
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) {
}
mDrawer.closeDrawer(GravityCompat.START);
return true;
}
}
dependencies
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
styles
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
styles-v21
<resources>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
</style>
</resources>
It's not clear exactly what your issue is (in what way did it not work?),
but perhaps you missed the fact that you muse actually define the 'drawer_header' layout and the 'drawer' menu?
If that's not the problem, please explain in more detail exactly what you're having a problem with.

I'm having an issue in Navigation view item click listener in androidx

I'm actually working on an app which includes navigation view and the app is running on androidx, I tried all the possible solutions from my point of view. Actual problem is onNavigationItemSelected is not calling even though I implemented NavigationView.OnNavigationItemSelectedListener to my base class.
My HomeActivity class which implements NavigationView.OnNavigationItemSelectedListener is
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "checkDate";
ActivityHomeBinding binding;
Context context;
LinearLayoutManager layoutManager;
HomeAdapter adapter;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
context = this;
binding = DataBindingUtil.setContentView(this, R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
drawerToggle = new ActionBarDrawerToggle(this, binding.drawer, R.string.open, R.string.close);
binding.drawer.addDrawerListener(drawerToggle);
drawerToggle.syncState();
drawerToggle.setDrawerIndicatorEnabled(false);
drawerToggle.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
List<EventDay> events = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
events.add(new EventDay(calendar, R.drawable.ic_event_black_24dp));
binding.homeLayout.calendarView.setEvents(events);
binding.homeLayout.calendarView.setOnDayClickListener(eventDay -> {
Toast.makeText(context, eventDay.getCalendar().getTime().toString(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onDayClick: "+Calendar.DAY_OF_MONTH);
});
layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(RecyclerView.VERTICAL);
adapter = new HomeAdapter(context);
binding.homeLayout.rvEvents.setNestedScrollingEnabled(true);
binding.homeLayout.rvEvents.setHasFixedSize(true);
binding.homeLayout.rvEvents.setAdapter(adapter);
binding.homeLayout.rvEvents.setLayoutManager(layoutManager);
binding.navView.setNavigationItemSelectedListener(this);
ItemClickSupport.addTo(binding.homeLayout.rvEvents).setOnItemClickListener((recyclerView, position, v) -> {
Intent intent = new Intent(context, SiteReachActivity.class);
startActivity(intent);
});
}
#Override
public void onBackPressed() {
if (binding.drawer.isDrawerOpen(GravityCompat.START)){
binding.drawer.closeDrawer(GravityCompat.START);
return;
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
binding.drawer.openDrawer(GravityCompat.START);
}
return true;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
Intent intent;
switch (id){
case R.id.menu_profile:
intent = new Intent(context, ProfileActivity.class);
startActivity(intent);
break;
case R.id.menu_dashboard:
break;
case R.id.menu_history:
intent = new Intent(context, HistoryActivity.class);
startActivity(intent);
break;
case R.id.menu_TADA:
break;
case R.id.menu_logOut:
break;
}
return true;
}
}
And the layout file is
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/white"
app:headerLayout="#layout/nav_header_main"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/activity_main_drawer"/>
<include
android:id="#+id/home_layout"
layout="#layout/home_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.drawerlayout.widget.DrawerLayout>
</layout>
And the layout file for activity_main_drawer is
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_profile"
android:icon="#drawable/user"
android:title="#string/user"/>
<item android:id="#+id/menu_dashboard"
android:icon="#drawable/home"
android:title="Dashboard"/>
<item android:id="#+id/menu_history"
android:icon="#drawable/history"
android:title="History"/>
<item android:id="#+id/menu_TADA"
android:icon="#drawable/wallet"
android:title="TADA"/>
<item
android:id="#+id/menu_logOut"
android:icon="#drawable/ic_power_settings_new_black_24dp"
android:title="Logout"/>
</menu>
In case anything more needed plese do comment. TIA
If you are using androidX then you have to use the NavController for navigation through fragments.
I will post the code I have tried
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavController mNavController;
Navigation mNavigation;
BottomNavigationView mBottomNavigationView;
NavigationView mNavigationView;
DrawerLayout mDrawerLayout;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerLayout = findViewById(R.id.drawer_layout);
mBottomNavigationView = findViewById(R.id.bottom_navigation_view);
mNavigationView = findViewById(R.id.navigation_view);
//mNavController = Navigation.findNavController(this,R.id.host_fragment);
mNavController = Navigation.findNavController(this,R.id.host_fragment);
NavigationUI.setupWithNavController(mBottomNavigationView,Navigation.findNavController(this,R.id.host_fragment));
NavigationUI.setupActionBarWithNavController(this, mNavController, mDrawerLayout);
NavigationUI.setupWithNavController(mNavigationView,mNavController);
mNavigationView.setNavigationItemSelectedListener(this);
//NavigationUI.setupActionBarWithNavController(this,Navigation.findNavController(this,R.id.host_fragment));
}
#Override
public boolean onSupportNavigateUp() {
/*return mNavController.popBackStack(R.id.host_fragment,false);*/
return NavigationUI.navigateUp(Navigation.findNavController(this, R.id.host_fragment), mDrawerLayout);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBackPressed() {
NavController navController = Navigation.findNavController(this, R.id.host_fragment);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.requireNonNull(navController.getCurrentDestination()).getId() == R.id.nav_first) {
finishAffinity();
} else {
mNavController.popBackStack(R.id.nav_first, false);
}
}
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
mDrawerLayout.closeDrawers();
int id = menuItem.getItemId();
switch (id){
//Nav drawer items
case R.id.profile:
mNavController.navigate(R.id.profile);
break;
case R.id.features:
mNavController.navigate(R.id.features);
break;
case R.id.signOut:
finishAffinity();
break;
}
return true;
}
}
You need to have the host fragment where you need to implement the fragments in the activity layout where you are implementing the Navigation
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="#android:color/white"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="10">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/toolbar_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="8"
android:gravity="center"
android:padding="10dp"
android:text="#string/jetpack_example"
android:textColor="#000"
android:textSize="15sp" />
<ImageView
android:id="#+id/search_bar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="2"
android:padding="10dp"
android:src="#drawable/about_icon" />
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="#android:color/white"
app:labelVisibilityMode="selected"
app:layout_constraintBottom_toBottomOf="#+id/host_fragment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu_drawer" />
<fragment
android:id="#+id/host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/navigation_graph"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/nav_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Next you need to have navigation graph for the navigation and using the arguments.You can also implement actions.Create a navigation folder and implement the below implementing the fragment when you click on the particular item.
navigation_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/navigation_graph"
app:startDestination="#id/nav_first">
<fragment
android:id="#+id/nav_first"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.FirstFragment"
android:label="#string/first"
tools:layout="#layout/fragment_first" />
<fragment
android:id="#+id/nav_second"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.SecondFragment"
android:label="#string/second"
tools:layout="#layout/fragment_second" />
<fragment
android:id="#+id/nav_third"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.ThirdFragment"
android:label="#string/third"
tools:layout="#layout/fragment_third" />
<fragment
android:id="#+id/nav_fourth"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.FourthFragment"
android:label="#string/fourth"
tools:layout="#layout/fragment_fourth" />
<fragment
android:id="#+id/profile"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.ProfileFragment"
android:label="#string/profile"
tools:layout="#layout/fragment_profile" />
<fragment
android:id="#+id/features"
android:name="com.escapadetechnologies.jetpacknavigationexample.Fragments.FeaturesFragment"
android:label="#string/features"
tools:layout="#layout/fragment_features" />
It is very handy and with the androidx lot of boilerplate code can be avoided. If you have any doubts you can comment on my answer.

FindViewByID from another layout

I have a problem.
I create a DrawerLayout and I use it as my MainLayout.
For my menu, I create a nav_header with two TextView.
Of course, when I try to modify the TextView, I got a null object reference, because the TextView are from another layout.
How can I setText for the TextView from another layout (specifically nav_header)?
I tried LayoutInflate but the problem doesn't disappear (probably i set things bad).
Can anyone help me?
MainActivity.java:
public class MainActivity extends AppCompatActivity{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private NavigationView navigationView;
private TextView logout_txt, name_txt;
private PermissionManager permissionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LayoutInflater layoutInflater = getLayoutInflater();
final View view = layoutInflater.inflate(R.layout.nav_header, null);
Log.d("USERNAME: ", ParseUser.getCurrentUser().getUsername());
name_txt = view.findViewById(R.id.txt_username_view);
name_txt.setText(ParseUser.getCurrentUser().getUsername());
ParseInstallation.getCurrentInstallation().saveInBackground();
init();
setUpDrawerContent(navigationView);
}
private void init() {
mDrawerLayout = findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = findViewById(R.id.nav_view);
logout_txt = findViewById(R.id.logout);
permissionManager = new PermissionManager() {};
permissionManager.checkAndRequestPermissions(this);
name_txt.setText(ParseUser.getCurrentUser().getUsername());
}
Nav_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="160dp"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:background="#drawable/main_header_selector"
android:padding="15dp"
tools:context=".MainActivity">
<ImageView
android:src="#drawable/ic_account"
android:layout_width="75dp"
android:layout_height="75dp" />
<TextView
android:id="#+id/txt_username_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textColor="#color/white"
android:textStyle="bold"
android:textSize="20sp" />
<TextView
android:id="#+id/txt_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12red.hawk12#gmail.com"
android:textColor="#color/white"
android:paddingTop="5dp"/>
</LinearLayout>
UPDATE:
I tried this code, and the applications starts, but the setText doesn't set text.
You are using a wrong method to use the drawerlayout. You could simply use the Navigation Drawer Activity in Android Studio for creating a navigation drawer. Navigation Drawer Layout automatically creates 4 layout files and a Java file for this purpose. I'm adding them right bellow-
MainActivity.java
package com.example.user.myapplication;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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 = 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 = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = 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();
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 = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Activity_main.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">
<include
layout="#layout/app_bar_main"
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" />
</android.support.v4.widget.DrawerLayout>
Content_main.XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.user.myapplication.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
App_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.myapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
All the Best.

Side Navigation Drawer Item click not working

PLEASE READ FIRST
BEFORE ANYONE MARK IT AS DUPLICATE QUESTION BECAUSE IT IS NOT.
I have used Navigation Drawer, Bottom Navigation bar and a custom Action bar.
Bottom navigation bar and action bar are working fine.
navigation drawer also shows menu present under it but the items are not clickable.
I have tried all the answers related to
navigation drawer item click not working
but still my problem has not been solved yet.
there is no error in the debug section.
Dashboard Activity
package com.vicky.sampleApp;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//android.app.ActionBar actionbar;
TextView textview;
TextView textviewTitle;
private ActionBar toolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
Toolbar toolbar1 = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar1);
setActionBarText("HomePage");
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar1, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.bringToFront();
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
toolbar = getSupportActionBar();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private void setActionBarText(String text){
toolbar = getSupportActionBar();
toolbar.setBackgroundDrawable(getResources().getDrawable(R.drawable.default_appbar_theme));//line under the action bar
View viewActionBar = getLayoutInflater().inflate(R.layout.actionbar_title_text_layout, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
textviewTitle = (TextView) viewActionBar.findViewById(R.id.actionbar_textview);
textviewTitle.setText(text);
toolbar.setCustomView(viewActionBar, params);
toolbar.setDisplayShowCustomEnabled(true);
toolbar.setDisplayShowTitleEnabled(false);
toolbar.setHomeButtonEnabled(true);
}
/*
private NavigationView.OnNavigationItemSelectedListener mSideNavigationItemSelectedListener
= new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.nav_camera:
Toast.makeText(Dashboard.this, "Camera", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Dashboard.this,AboutUs.class);
startActivity(intent);
break;
case R.id.nav_gallery:
Toast.makeText(Dashboard.this, "Gallery", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_slideshow:
Toast.makeText(Dashboard.this, "Slideshow", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_manage:
Toast.makeText(Dashboard.this, "Slideshow", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_share:
Toast.makeText(Dashboard.this, "Nav_share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_send:
Toast.makeText(Dashboard.this, "nav_send", Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
};
*/
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
setActionBarText("Home");
return true;
case R.id.navigation_appointments:
setActionBarText("Appointments");
return true;
case R.id.navigation_category:
setActionBarText("Category");
return true;
case R.id.navigation_profile:
setActionBarText("Profile");
return true;
}
return false;
}
};
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Toast.makeText(this, "Camera", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this,AboutUs.class);
startActivity(intent);
} else if (id == R.id.nav_gallery) {
Toast.makeText(this, "Gallery", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_slideshow) {
Toast.makeText(this, "Slideshow", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_manage) {
Toast.makeText(this, "Nav_manage", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_share) {
Toast.makeText(this, "Nav_share", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_send) {
Toast.makeText(this, "nav_send", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
dashboard.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">
<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" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/CustomTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/CustomTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:labelVisibilityMode="labeled"
app:itemBackground="#color/colorPrimary"
android:layout_gravity="bottom"
app:itemIconTint="#drawable/selector_bottom_nav_bar"
app:itemTextColor="#drawable/selector_bottom_nav_bar"
app:menu="#menu/navigation"/>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
Just put your NavigationView after FrameLayout. Check below code:
<?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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/CustomTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/CustomTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:labelVisibilityMode="labeled"
app:itemBackground="#color/colorPrimary"
android:layout_gravity="bottom"
app:itemIconTint="#drawable/selector_bottom_nav_bar"
app:itemTextColor="#drawable/selector_bottom_nav_bar"
app:menu="#menu/navigation"/>
</FrameLayout>
<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.v4.widget.DrawerLayout>
I was searching for different keywords but landed on this page every time. I had the issue that I could not click the navigation menu items.
I thought it would be easy to find a solution for those who are struggling with this strange behavior which is auto-generated by android studio 4.0 while creating a project with a navigation drawer.
I spent hours but at the end I have to find it my own way and that way was too simple. Posting in the hope of helping someone. My Layout was the following on which the item click was not working.
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
<com.google.android.material.navigation.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" />
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
I changed to this , Just put the navigation view on the bottom and it worked.
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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" />
<com.google.android.material.navigation.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" />
</androidx.drawerlayout.widget.DrawerLayout>
I too had the same problem. Just you have to put the NavigationView in the last part of the XML code.
You should call or include the frame layout
before next, the navigation refer to the code
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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" />
<com.google.android.material.navigation.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" />
</androidx.drawerlayout.widget.DrawerLayout>

Categories

Resources