issue with replacing Fragment views in Navigation drawer - android

I am using the android Navigation drawer template and fragments to display different views.
as the normal there is a MainActivity, activity_main.xml and content_main.xml generated automatically.
I have created two java classes; MusicFragment and MainFragment and of course the layout files which I have content inside.
When I run the app the activity_main is the default layout launched which I have welcome content displaying, I am using the Navigation drawer to navigate to my MusicFragment and MainFragment, this code I using to replace the current view in the onNavigationItemSelected method is;
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
these both work fine with replacing each other although I have a big problem, when I select the nav drawer and hit the camera option it shows the fragment view but does not replace the content from activity_main it shows the fragment content on top of the content_main and doesn't replace it.
This is my MainActivity:
package com.justmikey.justmik;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.internal.widget.ButtonBarLayout;
import android.text.method.ScrollingMovementMethod;
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.widget.Button;
import android.widget.TextView;
import JustMikey.Fragments.MainFragment;
import JustMikey.Fragments.MusicFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//create a media player object called mp
MediaPlayer mp;
//declare my buttons play, pause and stop
Button play, pause,stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the textView scrollMain to scrollable
TextView tv = (TextView) findViewById(R.id.scrollMain);
tv.setMovementMethod(new ScrollingMovementMethod());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior" tools:showIn="#layout/app_bar_main"
tools:context=".MainActivity"
android:background="#dbe4eb">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/content_frame">
<ImageView
android:layout_width="355dp"
android:layout_height="wrap_content"
android:src="#drawable/jmmain"
android:id="#+id/imageView2"
android:layout_gravity="center_horizontal|top"
android:layout_alignRight="#+id/content_frame"
android:layout_alignEnd="#+id/content_frame" />
<TextView
android:layout_width="fill_parent"
android:layout_height="274dp"
android:text="hello hello hello hello hello hello hello hello"
android:id="#+id/scrollMain"
android:layout_gravity="center_horizontal|bottom"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="28dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#ffffff"
android:padding="10dp"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center">
</ScrollView>
</FrameLayout>
</RelativeLayout>

FragmentTransactions only handle Fragments. They will not replace/remove anything not in a Fragment. Since those Views contained in the content_frame FrameLayout are only needed at startup, we can simply remove them upon the first FragmentTransaction.
To do this, we'll create a member boolean flag, isStartup, initialized to true. In the onNavigationItemSelected() method, we'll check the flag, and if it's true, remove the Views and change it to false.
Declare and initialize the boolean outside of any method:
private boolean isStartup = true;
Then do the check and removal in the onNavigationItemSelected() method.
public boolean onNavigationItemSelected(MenuItem item) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if(isStartup) {
((FrameLayout) findViewById(R.id.content_frame)).removeAllViews();
isStartup = false;
}
if (id == R.id.nav_camara) {
...
}

I had the same problem.
I could not solve my problem with the said solutions. But i found two solutions to solve it!
1- You can present the content of the main page into an other view group. and hide it in onNavigationItemSelected, in the right place:
content_main.xml:
<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:background="#dbe4eb"
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=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/my_linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/content_frame"
android:layout_alignRight="#+id/content_frame"
android:layout_gravity="center_horizontal|top"
android:src="#drawable/jmmain" />
<TextView
android:id="#+id/scrollMain"
android:layout_width="fill_parent"
android:layout_height="274dp"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="28dp"
android:background="#ffffff"
android:padding="10dp"
android:text="hello hello hello hello hello hello hello hello" />
<ScrollView
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center"></ScrollView>
</LinearLayout>
</RelativeLayout>
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
findViewById(R.id.my_linearLayout).setVisibility(View.VISIBLE);
fragmentManager.popBackStack("fragment", POP_BACK_STACK_INCLUSIVE);
} else if (id == R.id.one) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
2- The second way is to consider a fragment for the contents of the main page as well. and then in the onNavigationItemSelected method, we treat it Like the rest of the fragments:
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.one) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
note: To display the contents of the main page when opening the program enter the following code in onCreate() in MainActivity:
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();

Related

Android Navigation View click listener not working [duplicate]

This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
Closed 4 years ago.
I created the Activity with the Wizard.
I deleted what I am not interested in, for example, the floating action button.
Created my custom items in the activity_main_drawer.xml
The wizard created the onNavigationItemSelected function (see code below) and I added my code so it quits the activity and goes back to the Login Screen.
So I don't know why, I see nothing interesting in the logcat so this is a logical problem. I am a newbie and Navigation View scares me a lot... Let me know if I missed anything you need.
package com.skrefi.googleplaycopy;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
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;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//Don't know what this is
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//Don't know what this is either
#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;
}
//In case I need it for the admin activity >> the 3 dots pop down thingy <<
#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.
MakeToast("SOMETHING");
switch (item.getItemId()){
case R.id.action_settings:
MakeToast("Settings button clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void MakeToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
Edit:
So it may be confusing if I set the visibility to gone and I get use the layout I want right in this layout file because I get the screen without the toolbar, this is what I want. AND I want to keep that as well for the admin part, to check later in if the user is me, and if so, I get a new item in the drawer called Admin Activity which simply set the thingy visibility to visible so i get the admin screen.
Here is what you (#) asked for:
<?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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--This is for a potential admin screen-->
<include
android:id="#+id/include_toolbar_with_threedots_settings"
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<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.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is for test"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.DrawerLayout>
You're calling finish() before actually starting your activity while you should call it after starting your login activity. The following code will start Login activity and close the Main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}

Navigation drawer is below toolbar in Android [duplicate]

This question already has answers here:
How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?
(10 answers)
Closed 6 years ago.
Hello everyone,
I am a newcomer to Android programming and currently working on a practice app that is more or less a patchwork of tutorial codes.
Right now I have navigation drawer below toolbar. I would like to readjust xml hierarchy so that it stays consistent with Material Design guideline and have navigation drawer above toolbar. It seems like a simple enough task, but for the life of me I can't seem to get it.
Can anyone offer any suggestions?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:apps="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background_color">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/primary_color"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
apps:title="#string/app_name"/>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:apps="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</FrameLayout>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:apps="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
apps:itemTextColor="#000"
android:fitsSystemWindows="true"
apps:headerLayout="#layout/navigation_header"
apps:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
package android.dohyun.projectannie;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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 {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_layout, new NotesFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if(menuItem.getItemId() == R.id.menu_notes) {
FragmentTransaction fragmentTransactionNotes = mFragmentManager.beginTransaction();
fragmentTransactionNotes.replace(R.id.frame_layout, new NotesFragment()).commit();
}
if(menuItem.getItemId() == R.id.menu_folders) {
FragmentTransaction fragmentTransactionFolders = mFragmentManager.beginTransaction();
fragmentTransactionFolders.replace(R.id.frame_layout, new FoldersFragment()).commit();
}
if(menuItem.getItemId() == R.id.menu_trash) {
FragmentTransaction fragmentTransactionTrash = mFragmentManager.beginTransaction();
fragmentTransactionTrash.replace(R.id.frame_layout, new TrashFragment()).commit();
}
if(menuItem.getItemId() == R.id.menu_settings) {
FragmentTransaction fragmentTransactionSettings = mFragmentManager.beginTransaction();
fragmentTransactionSettings.replace(R.id.frame_layout, new SettingsFragment()).commit();
}
if(menuItem.getItemId() == R.id.menu_info) {
FragmentTransaction fragmentTransactionInfo = mFragmentManager.beginTransaction();
fragmentTransactionInfo.replace(R.id.frame_layout, new InfoFragment()).commit();
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
The above code is a slightly modified version of the one found here, written by Ratan:
https://androidbelieve.com/navigation-drawer-with-swipe-tabs-using-design-support-library/
DrawerLayout is a special FrameLayout that supports navigation drawer.
The child view that doesn't have a layout_gravity is the main view. The child view that has a layout_gravity e.g. android:layout_gravity="start" is the nav drawer.
This means that DrawerLayout should be the top level view group. In other words, put your layout with the Toolbar inside the DrawerLayout.

NullPointerException When starting new Activity in Navigation Drawer

I am using a template navigation drawer that was provided by android studio. I am very new to android development so i'm wondering if i'm missing something simple here. I want to start a new activity by clicking on an item in my navigation menu I followed several tutorials on how to do this but i keep getting this error in my logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
Here is the code I tried to start a new activity:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
}
else if (id == R.id.nav_gallery) {
Intent intent = new Intent(MainActivity.this, second_activity.class);
startActivity(intent);
}
else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I referred to my second activity in my manifest file like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
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=".second_activity">
<intent-filter>
<action android:name="com.example.bsmyth.sidemenu.second_activity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Here is the drawer layout:
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="Adfeed"
android:checked="true"/>
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="Post" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="Notification" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_send"
android:title="Messages" />
</group>
Here is the second activity:
package com.example.bsmyth.sidemenu;
import android.app.ActionBar;
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 second_activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is second_activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
And here are the error messages in logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.bsmyth.sidemenu.second_activity.onCreate(second_activity.java:30)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Your second activity layout has only a DrawerLayout and one TextView it does not have the views that you are calling in onCreate method.
Try running it again after removing this views from your onCreate:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
add this:
android:id="#+id/drawer_layout"
to your DrawerLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Use a little common sense on these, you are using findViewById for drawer_layout, toolbar as well as nav_view and other extras too.
But there is nothing in second_activity layout except one TextView even that is without any id. Then how can these codes work ?
Create these elements like shown in new android project in android studio then follow the same pattern and see how the next layout is included there.
Your will get multiple NullPointerException in your code. You only copied the code of MainActivity.java to second_activity.java but not in the layout file from activity_main to second_activity.
You can create your second activity in project explorer and selecting the activity you want from the template. It is the easiest way and also very good way. After that you can simply call the second activity from first activity like you are doing now
You are doing many things wrong in second activity code....
In layout XML..you don't give any id for drawer layout which you are using (drawer_layout).
So Add this...
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Also create this view toolbar and nav_view in this XML file like you have create Textview in second_activity XML .
And create Drawer object only once with same drwaer id(drawer_layout).
Like...
//declare this globally(means out of any method)
DrawerLayout drawer;
and then initialize this in onCreate method...
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
and at last remove this line DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); from onBackPressed() and onNavigationItemSelected method.
Hope this will help you...

Icon to open navigation drawer is missing in action bar of AppCompatActivity in Android

I am trying to use the android navigation drawer with the action bar of AppCompatActivity. But when I implement the action bar the icon to open the navigation drawer is missing in it.
This is what I want to be displayed
This is a screenshot of my current action bar
You can see my code below.
This is my 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"
android:id="#+id/main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"/>
<!--app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view" />-->
</android.support.v4.widget.DrawerLayout>
This is my action_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
This is my MainActivity
package com.blog.waiyanhein.llks.llks;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Why is the icon to open the navigation drawer missing using my code?
You didn't implement the NavigationDrawer in your Activityi guess.i've had the same problem and that fixed with the following code.
In your Activity:
private DrawerLayout drawerLayout;
In your onCreate:
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.home:
drawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
Strings.xml:
<string name="openDrawer">Navigation</string>
<string name="closeDrawer">Close Navigation</string>
Then it should work.
Try this code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
You may need to include:
actionBarDrawerToggle.syncState();
The answer here may help:
Appcompatv7 - v21 Navigation drawer not showing hamburger icon

Android drag margin for navigation drawer is off screen

I have recently created an app called Hoops and I have been developing it for quite some time now. However, the main problem that I seem to be getting, is that the navigation drawer's swipe margin is off screen and other users find it incredibly hard to use the navigation drawer's swipe feature. The menu button works just fine though. I have looked at other tutorials online and all of them seem to be showing the same answer as the one in the forum I have linked: Set drag margin for Android Navigation Drawer
However, I have tried this solution, and it does not seem to be working for me. If anyone has any ideas why it is not working please can you help me out. Here is the coding for the Main activity with the navigation drawer below:
package com.jehan.sportstutorials;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBar actionBar;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
if (navigationView != null) {
setupNavigationDrawerContent(navigationView);
}
setupNavigationDrawerContent(navigationView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
textView = (TextView) findViewById(R.id.textView);
switch (menuItem.getItemId()) {
case R.id.item_navigation_drawer_basketball:
menuItem.setChecked(true);
textView.setText(menuItem.getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
Intent i = new Intent(MainActivity.this, BasketballTutorial.class);
startActivity(i);
return true;
case R.id.item_navigation_drawer_help:
menuItem.setChecked(true);
textView.setText(menuItem.getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
Intent intent2 = new Intent(MainActivity.this, HelpScreen.class);
startActivity(intent2);
return true;
}
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"
android:id="#+id/navigation_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="#bool/fitsSystemWindows">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_kitkat_height"
android:background="?colorPrimary"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="?colorPrimaryDark"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/welcome"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/md_text"
android:singleLine="false"
android:padding="20dp"
android:gravity="center"
android:textStyle="bold"
android:textIsSelectable="false" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
android:text="#string/swipe"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/md_text"
android:singleLine="false"
android:padding="20dp"
android:gravity="center"
android:textSize="20sp"
android:textStyle="italic"
android:layout_marginBottom="30dp"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="?colorPrimaryDark"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="#drawable/action_bar_color"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ToolbarTheme"
android:layout_marginTop="25dp"/>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="#bool/fitsSystemWindows"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
app:theme="#style/NavigationViewTheme" />
If anyone wants a live example of the navigation drawers swipe feature not working you can test out my app in the app store. Here is the link: https://play.google.com/store/apps/details?id=com.jehan.sportstutorials
Summary: Does anyone know how to increase the navigation drawers drag margin, however not following the conventional methods stated in the link in my first paragraph? Help would be appreciated.
Check your R.layout.activity_main layout. Android Studio IDE, for some reason, sets 15dp margin to the topmost container of automatically-created Activity layouts. This could interfere with the Drawer.
Just check if the topmost Relative/Frame/Whichever Layout has any android:layout_marginX attributes set and remove them.

Categories

Resources