Ящик навигации андроида с сползать TabView

Я наткнулся на сумасшедшего маленького «жука», или я просто делаю что-то не так. Я пытаюсь получить вид вкладки салфетки в основной деятельности, салфетки tabView отлично работает, но основная проблема заключается в том, когда нажмите на меню навигационного ящика, то фрагмент накладываются друг на друга. пожалуйста помочь..

вот мой фрагмент двух tabView

1.NewsFragment

public class NewsFragment extends Fragment {

public static NewsFragment newInstance(){
    NewsFragment newsFragment=new NewsFragment();
    return newsFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.news_fragment,null);
}}

2.NoticeFragment

public class NoticeFragment extends Fragment {
public static NoticeFragment newInstance(){
    NoticeFragment noticeFragment=new NoticeFragment();
    return noticeFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.notice_fragment, container, false);
}}

Вот мои два xml для двух фрагментов

1.News_fragment.XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_layout_marginTop="120dp"
    android_textSize="30sp"
    android_gravity="center"
    android_id="@+id/textView"
    android_layout_centerHorizontal="true"
    android_textColor="@android:color/holo_blue_dark"
    android_text="NewsnFragment"/>

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_autoLink="web"
    android_textSize="15sp"
    android_layout_marginTop="10dp"
    android_layout_centerHorizontal="true"
    android_text="Android Sikkha"
    android_textColor="#000"
    android_layout_below="@+id/textView"
    android_textStyle="italic"/>
 </RelativeLayout>

2.notice_fragment.XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_layout_marginTop="120dp"
    android_textSize="30sp"
    android_gravity="center"
    android_id="@+id/textView"
    android_layout_centerHorizontal="true"
    android_textColor="@android:color/holo_blue_dark"
    android_text="NoticenFragment"/>

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_autoLink="web"
    android_textSize="15sp"
    android_layout_marginTop="10dp"
    android_layout_centerHorizontal="true"
    android_text="Android Sikkha"
    android_textColor="#000"
    android_layout_below="@+id/textView"
    android_textStyle="italic"/>

</RelativeLayout>

у меня есть еще один файл java под названием Home, который такой же, как предыдущий файл java, а также xml такой же.

Вот главное

package com.example.user.navwithtab;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
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 java.util.ArrayList;
import java.util.List;

 public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
 DrawerLayout drawer;
 ViewPager mViewPager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Setear adaptador al viewpager.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    setupViewPager(mViewPager);

    // Preparar las pestañas
    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(mViewPager);

    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);
}
private void setupViewPager(ViewPager viewPager) {
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(NewsFragment.newInstance(), "News");
    adapter.addFragment(NoticeFragment.newInstance(), "Notice");
    viewPager.setAdapter(adapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragments = new ArrayList<>();
    private final List<String> mFragmentTitles = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragments.add(fragment);
        mFragmentTitles.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles.get(position);
    }
}





@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();
    android.app.FragmentManager fragmentManager=getFragmentManager();

    if (id == R.id.home) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
    } else if (id == R.id.announcement) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).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;
}}

вот activity_main.XML

<?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.DrawerLayout 
 
 

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>

Извините за длинный пост.

Примечание: навигационный ящик и вид салфетки работают отлично, но проблема заключается в наложении фрагментов.после нажатия navigationbarmenu

Вот мой logcat

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.user.navwithtab, PID: 3400
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
                  at com.example.user.navwithtab.MainActivity.onNavigationItemSelected(MainActivity.java:157)
                  at android.support.design.widget.NavigationView

I stumbled into a crazy little 'bug', or i'm just doing something wrong. I am trying to get the swipe tab view in main activity, swipe tabView perfectly working but the main problem is when click on Navigation Drawer Menu then the fragment are overlaying each other. please Help..

here is my two tabView Fragment

1.NewsFragment

public class NewsFragment extends Fragment {

public static NewsFragment newInstance(){
    NewsFragment newsFragment=new NewsFragment();
    return newsFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.news_fragment,null);
}}

2.NoticeFragment

public class NoticeFragment extends Fragment {
public static NoticeFragment newInstance(){
    NoticeFragment noticeFragment=new NoticeFragment();
    return noticeFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.notice_fragment, container, false);
}}

Here is my two xml for two fragment

1.News_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_layout_marginTop="120dp"
    android_textSize="30sp"
    android_gravity="center"
    android_id="@+id/textView"
    android_layout_centerHorizontal="true"
    android_textColor="@android:color/holo_blue_dark"
    android_text="NewsnFragment"/>

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_autoLink="web"
    android_textSize="15sp"
    android_layout_marginTop="10dp"
    android_layout_centerHorizontal="true"
    android_text="Android Sikkha"
    android_textColor="#000"
    android_layout_below="@+id/textView"
    android_textStyle="italic"/>
 </RelativeLayout>

2.notice_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_layout_marginTop="120dp"
    android_textSize="30sp"
    android_gravity="center"
    android_id="@+id/textView"
    android_layout_centerHorizontal="true"
    android_textColor="@android:color/holo_blue_dark"
    android_text="NoticenFragment"/>

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_autoLink="web"
    android_textSize="15sp"
    android_layout_marginTop="10dp"
    android_layout_centerHorizontal="true"
    android_text="Android Sikkha"
    android_textColor="#000"
    android_layout_below="@+id/textView"
    android_textStyle="italic"/>

</RelativeLayout>

i have another java file called Home which is same as previous one java file and also xml is same.

Here is the MainActivity

package com.example.user.navwithtab;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
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 java.util.ArrayList;
import java.util.List;

 public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
 DrawerLayout drawer;
 ViewPager mViewPager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Setear adaptador al viewpager.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    setupViewPager(mViewPager);

    // Preparar las pestañas
    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(mViewPager);

    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);
}
private void setupViewPager(ViewPager viewPager) {
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(NewsFragment.newInstance(), "News");
    adapter.addFragment(NoticeFragment.newInstance(), "Notice");
    viewPager.setAdapter(adapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragments = new ArrayList<>();
    private final List<String> mFragmentTitles = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragments.add(fragment);
        mFragmentTitles.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles.get(position);
    }
}





@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();
    android.app.FragmentManager fragmentManager=getFragmentManager();

    if (id == R.id.home) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
    } else if (id == R.id.announcement) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).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;
}}

here is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.DrawerLayout 
 
 

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>

Sorry for long post.

Note: Navigation Drawer and swipe View working perfectly but the problem is on fragment overlay.after clicking navigationbarmenu

Here is my logcat

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.user.navwithtab, PID: 3400
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
                  at com.example.user.navwithtab.MainActivity.onNavigationItemSelected(MainActivity.java:157)
                  at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:153)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
                  at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:328)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at     android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

.onMenuItemSelected(NavigationView.java:153)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
at android.support.design.internal.NavigationMenuPresenter

I stumbled into a crazy little 'bug', or i'm just doing something wrong. I am trying to get the swipe tab view in main activity, swipe tabView perfectly working but the main problem is when click on Navigation Drawer Menu then the fragment are overlaying each other. please Help..

here is my two tabView Fragment

1.NewsFragment

public class NewsFragment extends Fragment {

public static NewsFragment newInstance(){
    NewsFragment newsFragment=new NewsFragment();
    return newsFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.news_fragment,null);
}}

2.NoticeFragment

public class NoticeFragment extends Fragment {
public static NoticeFragment newInstance(){
    NoticeFragment noticeFragment=new NoticeFragment();
    return noticeFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.notice_fragment, container, false);
}}

Here is my two xml for two fragment

1.News_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_layout_marginTop="120dp"
    android_textSize="30sp"
    android_gravity="center"
    android_id="@+id/textView"
    android_layout_centerHorizontal="true"
    android_textColor="@android:color/holo_blue_dark"
    android_text="NewsnFragment"/>

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_autoLink="web"
    android_textSize="15sp"
    android_layout_marginTop="10dp"
    android_layout_centerHorizontal="true"
    android_text="Android Sikkha"
    android_textColor="#000"
    android_layout_below="@+id/textView"
    android_textStyle="italic"/>
 </RelativeLayout>

2.notice_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical">

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_layout_marginTop="120dp"
    android_textSize="30sp"
    android_gravity="center"
    android_id="@+id/textView"
    android_layout_centerHorizontal="true"
    android_textColor="@android:color/holo_blue_dark"
    android_text="NoticenFragment"/>

<TextView
    android_layout_width="wrap_content"
    android_layout_height="wrap_content"
    android_autoLink="web"
    android_textSize="15sp"
    android_layout_marginTop="10dp"
    android_layout_centerHorizontal="true"
    android_text="Android Sikkha"
    android_textColor="#000"
    android_layout_below="@+id/textView"
    android_textStyle="italic"/>

</RelativeLayout>

i have another java file called Home which is same as previous one java file and also xml is same.

Here is the MainActivity

package com.example.user.navwithtab;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
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 java.util.ArrayList;
import java.util.List;

 public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
 DrawerLayout drawer;
 ViewPager mViewPager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Setear adaptador al viewpager.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    setupViewPager(mViewPager);

    // Preparar las pestañas
    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(mViewPager);

    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);
}
private void setupViewPager(ViewPager viewPager) {
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(NewsFragment.newInstance(), "News");
    adapter.addFragment(NoticeFragment.newInstance(), "Notice");
    viewPager.setAdapter(adapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragments = new ArrayList<>();
    private final List<String> mFragmentTitles = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragments.add(fragment);
        mFragmentTitles.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles.get(position);
    }
}





@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();
    android.app.FragmentManager fragmentManager=getFragmentManager();

    if (id == R.id.home) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
    } else if (id == R.id.announcement) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).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;
}}

here is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.DrawerLayout 
 
 

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>

Sorry for long post.

Note: Navigation Drawer and swipe View working perfectly but the problem is on fragment overlay.after clicking navigationbarmenu

Here is my logcat

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.user.navwithtab, PID: 3400
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
                  at com.example.user.navwithtab.MainActivity.onNavigationItemSelected(MainActivity.java:157)
                  at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:153)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
                  at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:328)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at     android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

.onClick(NavigationMenuPresenter.java:328)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 ответа

  1. В onNavigationItemSelectedметоде не создавайте DrawerLayoutснова. Просто позвоните closeDrawer.

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); --> remove this line of code
    drawer.closeDrawer(GravityCompat.START);
    

    ОБНОВЛЕНИЕ

    В методе onCreate измените эту строку кода

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    

    к

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    

    и добавьте эту строку кода

    DrawerLayout drawer
    

    под этой строкой кода

     ViewPager mViewPager;
    

    и удалить указанную строку кода в onNavigationItemSelectedметоде

  2. if (id == R.id.home) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
    } else if (id == R.id.announcement) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).commit();
    

    обновление выше кода, как показано ниже :

    if (id == R.id.home) {
    fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).addToBackStack(null).commit();
    } else if (id == R.id.announcement) {
    fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).addToBackStack(null).commit();