How to add even on ActionBarDrawerToggle? - android

Here is my program, but if I click nav_exit, my program is exiting. It isn't working as it should when I click. Help me please.
1.navigation_menu.xml
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_exit"
android:title="EXIT" />
<item
android:id="#+id/nav_gallery"
android:title="gallery" />
</group>
<item android:title="ssssssss">
<menu>
<item
android:id="#+id/nav_share"
android:title="share" />
<item
android:id="#+id/nav_se2nd"
android:title="se2nd" />
<item
android:id="#+id/nav_send"
android:title="send" />
</menu>
</item>
2.MainActivity is not working on click menu.
package info.mt_online.www.myapplicationv1;
import android.content.Intent;
import android.provider.Settings;
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.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
int id = item.getItemId();
if (id == R.id.nav_exit) {
finish();
System.exit(0);
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
It is not working. Can you please tell me why?

I guess you are trying to exit app using NavigationView menu Item. To do this, you have to implement NavigationItemSelectedListener and in method onNavigationItemSelected() check your desired nav_exit and exit from the application by calling finish().
Add below code in your MainActivity inside onCrate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
...........
.................
// NavigationView
NavigationView mNavigationView = (NavigationView) findViewById(R.id.your_navigation_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_exit) {
finish();
}
return true;
}
});
}
FYI, onOptionsItemSelected() is used for handling Toolbar option MenuItems click events.

Related

Items on NavigationDrawer are not Clicking

I have used Android Studio's inbuilt Navigation Drawer Activity and only the main fragment seems to be working, The other items in the drawer are not clicking or working. Please help.
MainActivity.java
package com.example.duzol;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
private static final int MAIN_FRAGMENT = 0;
private static final int TRACK_FRAGMENT = 1;
private FrameLayout frameLayout;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private static int currentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.nav_open_drawer, R.string.nav_close_drawer);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView!=null) {
navigationView.setNavigationItemSelectedListener(this);
}
navigationView.getMenu().getItem(0).setChecked(true);
frameLayout = (FrameLayout) findViewById(R.id.main_frameLayout);
setFragment(new MainFragment(),MAIN_FRAGMENT);
}
#Override
public void onBackPressed() {
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
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.
if (currentFragment == MAIN_FRAGMENT){ // menu inflates only if user is in main fragment
getMenuInflater().inflate(R.menu.main, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_bag) {
Toast.makeText(this, "Bag clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
item.setChecked(true);
drawerLayout.closeDrawers();
switch (id) {
case R.id.nav_home:
setFragment(new MainFragment(),MAIN_FRAGMENT);break;
case R.id.nav_track:myTrack();break;
case R.id.nav_appointment:
case R.id.nav_feedback:
Intent intent = new Intent(this, feedBackActivity.class);
startActivity(intent);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void myTrack(){
setFragment(new TrackFragment(),TRACK_FRAGMENT);
navigationView.getMenu().getItem(1).setChecked(true);
}
private void setFragment(Fragment fragment, int fragmentNum){
currentFragment = fragmentNum;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(frameLayout.getId(),fragment);
ft.commit();
}
}
ActivityMain.xml
I have used Navigation Drawer before but i used it from scratch (i.e. Empty Activity) but now after using the template the same stuff doesn't work. I don't know what I am doing wrong, I have checked it multiple times.
<?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>
Activity_main_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">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_baseline_notes_24"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_track"
android:icon="#drawable/ic_baseline_pin_drop_24"
android:title="#string/menu_track" />
<item
android:id="#+id/nav_appointment"
android:icon="#drawable/ic_baseline_timelapse_24"
android:title="#string/menu_appointment" />
</group>
<item android:title="Support">
<group android:checkableBehavior="single">
<item android:id="#+id/nav_feedback"
android:icon="#drawable/ic_baseline_mail_24"
android:title="#string/feedback"/>
</group>
</item>
</menu>
The issue is in your layout.
Change
<androidx.drawerlayout.widget.DrawerLayout>
<com.google.android.material.navigation.NavigationView/>
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
to:
<androidx.drawerlayout.widget.DrawerLayout>
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView/>
</androidx.drawerlayout.widget.DrawerLayout>

I'm creating a Navigation Drawer in android studio and I can not set the clicks on the items

I'm using android studio 3.1.3 I did not find the error, I followed a tutorial but in my case it did not work I searched the source code and found nothing and different follow link:
https://github.com/CursoAndroidMaterialDesign/Navigation-Drawer
Please Help
Main Activity:
package com.example.italo.nvigationdrawer;
import android.support.annotation.NonNull;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawerLayout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout,toolbar,R.string.open_drawer,R.string.close_drawer);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menu_inbox:{
Toast.makeText(this,"Menu Inbox" , Toast.LENGTH_SHORT).show();
break;
}
case R.id.menu_starred:{
Toast.makeText(this,"Menu Favoritos", Toast.LENGTH_SHORT).show();
break;
}
case R.id.menu_sent_email:{
Toast.makeText(this, "Menu Enviados", Toast.LENGTH_SHORT).show();
break;
}
case R.id.menu_trash:{
Toast.makeText(this, "Menu Lixeira", Toast.LENGTH_SHORT).show();
break;
}
case R.id.menu_spam:{
Toast.makeText(this, "Menu Spam", Toast.LENGTH_SHORT).show();
break;
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
main activit xml:
<?xml version="1.0" encoding="utf-8"?>
android:id="#+id/drawerLayout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_nav"
/>
<include layout="#layout/toolbar"/>
Menu class:
<?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:title="#string/inbox"
android:id="#+id/menu_inbox"
android:icon="#drawable/ic_inbox"/>
<item android:title="#string/favoritos"
android:id="#+id/menu_starred"
android:icon="#drawable/ic_starred"/>
<item android:title="#string/emails_enviados"
android:id="#+id/menu_sent_email"
android:icon="#drawable/ic_sent_email"/>
</group>
<item android:title="#string/outros"
android:id="#+id/submenu_outros">
<menu>
<item android:title="#string/lixeira"
android:id="#+id/menu_trash"
android:icon="#drawable/ic_trash"/>
<item android:title="#string/spam"
android:id="#+id/menu_spam"
android:icon="#drawable/ic_spam"/>
</menu>
</item>
</menu >
Result:
enter image description here
you have to add menu tag at the root level in Menu class:
<?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:title="#string/inbox"
android:id="#+id/menu_inbox"
android:icon="#drawable/ic_inbox"/>
<item android:title="#string/favoritos"
android:id="#+id/menu_starred"
android:icon="#drawable/ic_starred"/>
<item android:title="#string/emails_enviados"
android:id="#+id/menu_sent_email"
android:icon="#drawable/ic_sent_email"/>
</group>
<item android:title="#string/outros"
android:id="#+id/submenu_outros">
<menu>
<item android:title="#string/lixeira"
android:id="#+id/menu_trash"
android:icon="#drawable/ic_trash"/>
<item android:title="#string/spam"
android:id="#+id/menu_spam"
android:icon="#drawable/ic_spam"/>
</menu>
</item>
</menu >
In your onNavigationItemSelected method try replacing break; with return true; statement
use this code in your drawer project.
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (menuItemWaiting != null) {
onNavigationItemSelected(menuItemWaiting);
}
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
and then add define
onNavigationItemSelected( final MenuItem item ){
menuItemWaiting = null;
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
menuItemWaiting = item;
drawerLayout.closeDrawers();
return false;
}
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
fragment = new HomeFragment();
drawerLayout.closeDrawer(Gravity.START);
break;
}
}

How can we make an Activity appear by default at launch?

I made an app with navigation drawer whose default activity at startup is HomeActivity. I want it to the UserActivity to start by default at launch. I tried doing it with AndroidManifest.xml but it didn't work. Can u tell me another way of doing it like using intent or something in the HomeActivity such that it loads to UserActivity as soon as the app opens?
HomeActivity.java
package thenerdimite.nuttybuddies;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
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;
import android.view.ViewGroup;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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.home, 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();
android.app.FragmentManager fragmentmanager = getFragmentManager();
if (id == R.id.nav_activity_user) {
fragmentmanager.beginTransaction()
.replace(R.id.content_frame
, new UserActivity())
.commit ();
} else if (id == R.id.nav_activity_blog) {
fragmentmanager.beginTransaction()
.replace(R.id.content_frame
, new BlogActivity())
.commit ();
} else if (id == R.id.nav_activity_Chat) {
fragmentmanager.beginTransaction()
.replace(R.id.content_frame
, new ChatActivity())
.commit ();
} else if (id == R.id.nav_activity_fbgroup) {
fragmentmanager.beginTransaction()
.replace(R.id.content_frame
, new FBGroupActivity())
.commit ();
} 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;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thenerdimite.nuttybuddies">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BlogActivity" />
<activity android:name=".ChatActivity" />
<activity android:name=".FBGroupActivity" />
<activity android:name=".UserActivity"></activity>
</application>
</manifest>
UserActivity.java
package thenerdimite.nuttybuddies;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class UserActivity extends Fragment {
View myView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.activity_user, container, false);
return myView;
}
}
activity_home_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/nav_activity_user"
android:icon="#drawable/ic_menu_camera"
android:title="Home" />
<item
android:id="#+id/nav_activity_blog"
android:icon="#drawable/ic_menu_gallery"
android:title="Blog" />
<item
android:id="#+id/nav_activity_Chat"
android:icon="#drawable/ic_menu_slideshow"
android:title="Chat Room" />
<item
android:id="#+id/nav_activity_fbgroup"
android:icon="#drawable/ic_menu_manage"
android:title="Facebook Group" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="About Us" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="Click Here to Report App related Issues" />
</menu>
</item>
</menu>
Any help would be great. Thank You!
Add onNavigationItemSelected in OnCreate of HomeActivity.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
......
......
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
MenuItem item = navigationView.getMenu().getItem(0);
onNavigationItemSelected(item);
}
}
}
And remove this line From AndroidManifest.xml
<activity android:name=".UserActivity"></activity>
In AndroidManifest delete this
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
And add it to the activity you want to show at start
Hello #Bhavesh I thought you are using fragment so you doesn't need to declare in manifest just put last in on create method you will be in UserActivity
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new UserActivity())
.commit();

Android Navigation Draver

Can some one please tell me how to create activities to this MainActivity that the Navigation Drawer will be seen in all of them? I need to use this specific MainActivity code. I don't need to use fragments, just 3 simple activities will be added to this drawer.
import android.content.Intent;
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 = (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();
if (id == R.id.nav_ingredients) {
Intent intent = new Intent(getApplicationContext(),IngredientsActivity.class);
startActivity(intent);
} else if (id == R.id.nav_recepies) {
} else if (id == R.id.nav_grocery_list) {
} 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;
}
}
NavDrawer layout :
<?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_ingredients" android:icon="#mipmap/ingredients"
android:title="#string/ingredients" />
<item android:id="#+id/nav_recepies" android:title="#string/recipies"
android:icon="#mipmap/recepies"
/>
<item android:id="#+id/nav_grocery_list" android:icon="#mipmap/list"
android:title="#string/grocery_list" />
</group>
<item android:title="Communicate">
<menu>
<item android:id="#+id/nav_share" android:icon="#android:drawable/ic_menu_share"
android:title="Share" />
<item android:id="#+id/nav_send" android:icon="#android:drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
</menu>
Here is a complete example using the official Android Design Library
Also, here is some basic training using fragments in case you are not familiar with them.
One way to go would be to have your activities extend MainActivity.
In the other activities, you don't call setContentView instead, do this:
View contentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = inflater.inflate(R.layout.layout_for_the_activity, null, false);
mDrawer.addView(contentView, 0);
where mDrawer is defined in your MainActivity like this:
protected DrawerLayout mDrawer;
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
This is explained in more detail here

getActionBar() returns null in api 19, targets api 21 min sdk 16

My app is crashing on devices running kitkat(api 19), i tried on LG g3 and on a nexus 7 2013 because of nullPointer expection.
I found out that when I do getActionBar() it returns null and I cant fix it.
I use the appcompat theme 21 and the material theme for devices running lollipop, that on them the app works fine.
MainActivity.java:
package com.sqvat.betterpowermat;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private ActionBar actionBar;
private String[] categories;
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private String drawerClose;
private String drawerOpen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
//Nav Drawer
categories = getResources().getStringArray(R.array.categories);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.nav_drawer_li, R.id.drawer_li_textview, categories));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawerOpen, R.string.drawerClose) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(drawerToggle);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
selectItem(0);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (position){
case 0:
fragmentTransaction.replace(R.id.content_frame, new HomeFragment());
actionBar.setTitle("Home");
break;
case 1:
fragmentTransaction.replace(R.id.content_frame, new LocationsFragment());
actionBar.setTitle("Locations");
break;
case 2:
fragmentTransaction.replace(R.id.content_frame, new StoreFragment());
actionBar.setTitle("Store");
break;
case 3:
fragmentTransaction.replace(R.id.content_frame, new MoreFragment());
actionBar.setTitle("More");
break;
}
fragmentTransaction.commit();
drawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
#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;
}
}
my appcompat style (values/styles.xml):
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
</style>
<color name="colorPrimary">#4CAF50</color>
<color name="colorPrimaryDark">#43A047</color>
my android lollipop style (values-v21/styles.xml):
<style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
<item name="android:colorPrimary">#color/colorPrimary</item>
<item name="android:colorPrimaryDark">#color/colorPrimaryDark</item>
</style>
If you want to use ActionBar on support library, you have to extend ActionBarActivity class instead of Activity, and use getSupportActionBar() in place of getActionBar() to get ActionBar.
I have also faced this issue. I just removed
values-v21/styles.xml
Then it works fine without any crash.

Categories

Resources