1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.example.android.support.design.widget; 18 19import android.os.Bundle; 20import android.util.TypedValue; 21import android.view.MenuItem; 22import android.view.View; 23 24import androidx.appcompat.widget.Toolbar; 25import androidx.core.view.GravityCompat; 26import androidx.drawerlayout.widget.DrawerLayout; 27 28import com.example.android.support.design.R; 29import com.google.android.material.navigation.NavigationView; 30 31/** 32 * This demonstrates basic usage of NavigationView 33 */ 34public class NavigationViewUsage extends NavigationViewUsageBase { 35 36 private DrawerLayout mDrawerLayout; 37 38 @Override 39 protected void onCreate(Bundle savedInstanceState) { 40 super.onCreate(savedInstanceState); 41 42 mDrawerLayout = findViewById(R.id.drawer_layout); 43 44 // Set the color of status bar 45 TypedValue value = new TypedValue(); 46 getTheme().resolveAttribute(R.attr.colorPrimaryDark, value, true); 47 mDrawerLayout.setStatusBarBackgroundColor(value.data); 48 49 // Retrieve the Toolbar from our content view, and set it as the action bar 50 Toolbar toolbar = findViewById(R.id.toolbar); 51 setSupportActionBar(toolbar); 52 53 // Toggle icon 54 toolbar.setNavigationIcon(R.drawable.ic_action_navigation_menu); 55 toolbar.setNavigationOnClickListener(new View.OnClickListener() { 56 @Override 57 public void onClick(View view) { 58 mDrawerLayout.openDrawer(GravityCompat.START); 59 } 60 }); 61 } 62 63 @Override 64 protected int getLayout() { 65 return R.layout.design_navigation; 66 } 67 68 @Override 69 public NavigationView.OnNavigationItemSelectedListener getNavigationItemSelectedListener() { 70 return new NavigationView.OnNavigationItemSelectedListener() { 71 @Override 72 public boolean onNavigationItemSelected(MenuItem item) { 73 if (handleNavigationItemSelected(item)) { 74 mDrawerLayout.closeDrawers(); 75 return true; 76 } 77 return false; 78 } 79 }; 80 } 81 82 @Override 83 public void onBackPressed() { 84 if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { 85 mDrawerLayout.closeDrawer(GravityCompat.START); 86 } else { 87 super.onBackPressed(); 88 } 89 } 90 91} 92