What I have been Trying to Do
What I have been aiming to do for several days is, using an Activity that implements NavigationView.OnNavigationItemSelectedListener. I want this to create two Tabs inside a android.support.v4.app.Fragment in the FrameLayout provided by the template for the Navigation Drawer on Android Studio 1.5.1.
- My Current Activity uses a toolbar not an ActionBar.
- I was hoping to use a ViewPager; hence needing to use Support Fragments.
- I have followed several code examples online and have looked at Android Developers Reference.
Other Linked Posts:
Unable to add Tabs inside Fragment of Navigation Drawer Android | This uses Fragments and the ActionBar
Android TabHost inside Fragment | Chosen Answer -> using FragmentActivity | Unfortunatly uses a new FragmentActivity but I need to keep my NavigationDrawer so am using one activity
Android TabHost only inside one Fragment (NavigationDrawer) | This didnt really provide me much help as I am very new to using tabs
Android Adding Tab inside Fragment | Chosen Answer -> using FragmentTabHost | I have taken FragmentTabHost XML and Java code from this example but It has not worked
Tabs in a class that extends fragment | The andswer refers to googles documentation which is not working for me.
Adding Tab inside Fragment In Android? | Uses android.app.Fragment and the suggested answer didnt work.
Using TabLayout inside a Fragment; tab text invisible | I am using Design Library v23.1.1 | Bugs reported in v22.2.1. The code here gave me no tabs either
Any Suggestion would be appreciated.
MY CODE
NavActivity Class
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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;
public class NavigationMenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navmenu_act);
//Setting up the Toolbar
toolbar = (Toolbar) findViewById(R.id.navmenu_appbar_tbar);
setSupportActionBar(toolbar);
//Set up the action bar toggle
drawerLayout = (DrawerLayout) findViewById(R.id.navmenu_act_drawerlay);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
//Set up the navigation View
navigationView = (NavigationView) findViewById(R.id.navmenu_nav_view);
navigationView.setNavigationItemSelectedListener(this);
//SET THE FRAGMENT
fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.navmenu_appbar_fl);
if(fragment==null) { //If no fragment exists relate the fragment
fragment = new TabLayoutFragmentExample();
fragmentManager.beginTransaction()
.add(R.id.navmenu_appbar_fl, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.navmenu_act_drawerlay);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.navmenu_appbar_fl);
if(fragment!=null) { //If a fragment exists replace the fragment
fragment = new TestFragmentNoTabs();
fragmentManager.beginTransaction()
.replace(R.id.navmenu_appbar_fl, fragment)
.commit();
}
} else if (id == R.id.nav_near_me) {
// Handle the near me action here
} else if (id == R.id.nav_proximity) {
// Handle the proximity action
fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.navmenu_appbar_fl);
if(fragment!=null) {//If A fragment exists replace the fragment
fragment = new TestFragmentNoTabsTWO();
fragmentManager.beginTransaction()
.replace(R.id.navmenu_appbar_fl, fragment)
.commit();
}
}
//Close the drawerLayout after it is clicked?
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.navmenu_act_drawerlay);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//sync the toggle
toggle.syncState();
}
}
navmenu_appbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".NavigationMenuActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/navmenu_appbar_tbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/JethrosTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/navmenu_appbar_fl"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</android.support.design.widget.CoordinatorLayout>
TablayoutFragmentExample Class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class TabLayoutFragmentExample extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.tab_layout_frag, container, false);
TabLayout tabLayout = (TabLayout) inflatedView.findViewById(R.id.tab_layout_frag_tl);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
final ViewPager viewPager = (ViewPager) inflatedView.findViewById(R.id.tab_layout_frag_vp);
viewPager.setAdapter(new PagerAdapter //ChildFragManager; Tnx #Luksprog
(getChildFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager); //Set Viewpager; Tnx #Luksprog
return inflatedView;
}
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TestFragmentNoTabs tab1 = new TestFragmentNoTabs();
return tab1;
case 1:
TestFragmentNoTabsTWO tab2 = new TestFragmentNoTabsTWO();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
tab_layout_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
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.support.design.widget.TabLayout
android:id="#+id/tab_layout_frag_tl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/tab_layout_frag_vp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
</android.support.design.widget.AppBarLayout>
TestFragmentNoTabs & TestFragmentNoTabsTWO (Fragment 1 and fragment 2)
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public class TestFragmentNoTabs extends Fragment {
public final String TAG = "TestFragmentNoTabs";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the fragment view
View view = inflater.inflate(R.layout.testfragnotabs, container, false);
return view; //Return the view to the activity
}
#Override
public void onPause() {
super.onPause();
}
}
testfragnotabs.xml (similar to testfragnotabstwo.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nearme_frag_rlay"
android:clickable="false">
<TextView
android:id="#+id/nearme_frag_tv_seclab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" TestFragmentNoTabsOne -> testfragnotabs.xml" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView1"
android:layout_above="#+id/nearme_frag_tv_seclab" />
</RelativeLayout>
Current Situation with Above Code
The project builds fine and the navigation drawer is working fine as well. However the frame layout where the fragment and the TabLayout should appear is empty with a white background (Just like the Design preview in tab_layout_frag.xml; this could mean there is a problem with the ViewPager or the TabLayout?).
Related
Respected programmers of stack overflow,
I am very new to the world of programming and am actually trying to build an app to help my fellow medical students.
In my app I can't seem to be able to change fragments after pressing buttons on the navigation bar. Only a single fragment loads at first (home fragment) and the rest do not change at all.
Since I am new to the programming world it may just be a small mistake on my part, but I do hope you all can guide me.
Here is my MainActivity java file
public class MainActivity extends AppCompatActivity {
BottomNavigationView bnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bnView=findViewById(R.id.bnView);
bnView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id=item.getItemId();
if (id==R.id.home) {
loadfrag(new Homefragment(), true);
}else if(id==R.id.subject_based) {
loadfrag(new subjectfragment(), false);
}else if(id==R.id.about) {
loadfrag(new aboutfragment(), false);
}else if(id==R.id.exam) {
loadfrag(new examfragment(), false);
}else {
loadfrag(new paperfragment(), false);
}
return true;
}
});
bnView.setSelectedItemId(R.id.home);
}
public void loadfrag(Fragment fragment, boolean flag){
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
if (flag)
ft.add(R.id.container,fragment);
else
ft.replace(R.id.container,fragment);
ft.commit();
}
}
My main activity xml file is as follows;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/goojasto"
tools:context="com.cringyprithak.mcqrunch_3.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bnView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#EFD115"
app:menu="#menu/nav_items" />
</RelativeLayout>
My menu is as follows
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/subject_based"
android:icon="#drawable/ic_sub"
android:title="Subject-wise"/>
<item
android:id="#+id/paper"
android:icon="#drawable/ic_paper"
android:title="Paper-wise"/>
<item
android:id="#+id/home"
android:icon="#drawable/ic_home"
android:title="Home"/>
<item
android:id="#+id/exam"
android:icon="#drawable/ic_exam"
android:title="Exam Practice"/>
<item
android:id="#+id/about"
android:icon="#drawable/ic_action_name"
android:title="About Me"/>
</menu>
and an example of the coding in my fragments would be
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class aboutfragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_homefragment, container, false);
return view;
}
}
I have been trying all day to make a bottom navigation bar and have fragments switch according to the buttons in the navigation bar but I haven't been able to.
I've watched countless videos and tried anything I could find. Please help me.
Your code is fine in general. It is the proper way to switch between Fragment by using BottomNavigationBar.
Just a small change for following function. You can directly use replace() when switching between Fragment:
// Removed the boolean flag and use replace() directly
public void loadfrag(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// Can remove the add() function and just use replace()
ft.replace(R.id.container, fragment);
ft.commit();
}
So I guess the problem you encounter is when you try to load the view to your Fragment.
For your aboutfragment, you are trying to load R.layout.fragment_homefragment. And from the naming seems that it is a HomeFragment layout rather than your aboutfragment layout. You should have a your aboutfragment layout there:
public class aboutfragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Should replace R.layout.fragment_homefragment with your aboutfragment layout
view = inflater.inflate(R.layout.fragment_homefragment, container, false);
return view;
}
}
And for better practice, please follow Java Naming Convention when you are creating functions or classes.
For example:
Homefragment should be in HomeFragment
aboutfragment should be in AboutFragment
I've seen many posts on this matter, but I can't figure it out for my code. I have created a tabbed activity and set three buttons at the bottom. The buttons switch between different fragments. A button in a MainActivity opens this tabbed activity, but the problem is that the fragment layout is empty (see image below).
The buttons work perfectly and send me to the right fragments, but when it opens, no fragments are loaded.
The code, which I build following an YouTube tutorial looks like this:
TabbedActivity.class
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class TabbedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed_activity);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
int intentFragment = getIntent().getExtras().getInt("frgToLoad");
switch (item.getItemId()) {
case R.id.navigation_home:
transaction.replace(R.id.content,new Fragment_B1()).commit();
/* mTextMessage.setText(R.string.title_home);*/
return true;
case R.id.navigation_dashboard:
transaction.replace(R.id.content,new Fragment_B2()).commit();
/*mTextMessage.setText(R.string.title_dashboard);*/
return true;
case R.id.navigation_notifications:
transaction.replace(R.id.content,new Fragment_B3()).commit();
/*mTextMessage.setText(R.string.title_notifications);*/
return true;
}
return false;
}
};
}
The fragments have the same code pattern inside, which is basic and it makes no point to add it here. The xml of the TabbedActivity looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="TabbedActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="#+id/appbar">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Can anyone help me to figure out how to open Fragment_B1 by default? I have tried adding the code from the best answer from here, but still doesn't work.
You can just added the original fragment direct on the onCreate, like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed_activity);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
if(savedInstanceState == null) {
getSupportFragmentManager().
beginTransaction().replace(R.id.content,new Fragment_B1()).commit();
}
}
In the last add, navigation.setSelectedItemId(navigation_home);
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.
Hello I am new to android, I am currently trying to navigate from my MainActivity to a TabbedActivity. I created a new TabbedActivity using the default Tabbed Activity template in the Gallery in Android Studio.
However after the files were created, I checked the code and saw that many lines of code used in creating the Activity were cross out, meaning they were deprecated.
I tried running the app, it worked until I tried to navigate to this Tabbed Activity then it crashed and threw an error in my Android Monitor.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxx.eventmanager/com.xxxxxx.eventmanager.EventDetailsActivity}: 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.xxxxxx.eventmanager.EventDetailsActivity.onCreate(EventDetailsActivity.java:42)
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)
This is my Tabbed Activity named EventDetailsActivity. I have not added any custom code or made any changes to the default code that was generated on create:
package com.xxxxxx.eventmanager;
import android.app.Activity;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class EventDetailsActivity extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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_event_details, 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);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_event_details, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
I am new to both Java and Android and quite perplexed by this.
try to change this line
final ActionBar actionBar = getActionBar();
TO
final ActionBar actionBar = getSupportActionBar();
use extends AppCompatActivity and use use the toolbar as..
private void setup_tabs(){
pager = (CustomViewPager)findViewById(R.id.viewpager);
pager.setOffscreenPageLimit(3);
adapter = new Tabs_Pager_adapter(getSupportFragmentManager(),this);
pager.setAdapter(adapter);
pager.setPagingEnabled(true);
// Title.setText(adapter.getPageTitle(pager.getCurrentItem()));
tabLayout = (TabLayout) findViewById(R.id.tabs);
// tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Respondents"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
tabLayout.setupWithViewPager(pager);
}
private void setupToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar != null)
setSupportActionBar(toolbar);
// Show menu icon
final ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowTitleEnabled(false);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
And in your layout..
<LinearLayout
android:layout_weight=".75"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"/>
<your.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And this the theme..
<style name="Base.Theme.your_theme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/my_primary</item>
<item name="colorPrimaryDark">#color/my_primary_dark</item>
<item name="colorAccent">#color/my_accent</item>
</style>
Use the app compat library with android support library... and with design support library.. it is awesome. use the tooolbar layout in your layout.xml
and set the theme with appcompat with no actionbar.
How I treat with toolbar in my app (for example).
In my activity layout xml file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<!-- more xml code below -->
Content of toolbat.xml:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/PopupMenuStyle"
android:background="#color/bar_color">
<!-- arbitrary components are in toolbar -->
</android.support.v7.widget.Toolbar>
Now I prepared for set up the toolbar in my app. In onCreate method I have to use this code before using toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
Since that moment I can use getSupportActionBar() and it will return correct result.
In your case you may use setActionBar(toolbar) instead of setSupportActionBar(toolbar) and <android.widget.Toolbar instead of <android.support.v7.widget.Toolbar in your layout file.
I had Created a Home activity which includes Tablayout and Navigation Drawer onclick with fragment. I had included fragmentTransaction.addToBackStack(null).commit(); with the fragment transaction code to go back to previous Activity.
My Desired requirement was From Activity with tablayout-->NavigationDrawer-->Fragment1--> On BackButtonPress-->MainActivity with tablayout.
But,Now i am able to move to Fragment1,and when return to MainActivity,the view becomes filled with white(if i use mainLayout.removeAllViews(); and if wont use mainLayout.removeAllViews(); ,then the fragment is overlapping with the MainActivity)
1.My mainactivty
2.fragment
3.when i return to mainactivty
Now i cant see tablayout in my MainActivity.
Can anyone please help me.
mainactivity_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/mainlayout"
tools:showIn="#layout/app_bar_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
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.RelativeLayout;
import java.io.File;
import java.util.ArrayList;
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);
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);
TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));
tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
final PagerAdapter1 adapter = new PagerAdapter1
(getSupportFragmentManager(), tabLayout1.getTabCount());
viewPager1.setAdapter(adapter);
viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Handle navigation view item clicks here.
int id = item.getItemId();
RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_content);
if (id == R.id.nav_login) {
LoginFragment fragment = new LoginFragment();
// mainLayout.removeAllViews();
fragmentTransaction.replace(R.id.mainlayout, fragment);
fragmentTransaction.addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class ContactFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
Button call;
public ContactFragment() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_contact,container,false);
call = (Button) v.findViewById(R.id.button5);
call.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:7034409615"));
startActivity(i);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(9.2700, 76.7800);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Pathanamthitta"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
As I suggested in the comments, in order to figure out the problem with displaying of fragments you can try to view what kind of fragments are being added into back stack as follows
Log.d("FragmentList",getSupportFragmentManager().getFragments().toString();
You can put it inside onBackPressed() ,onNavigationItemSelected()
According to your feedback it was helpful for you and you figured out the problem.
Also there are some layout design issues:
Your current approach is to adding fragment into relative layout. I believe it leads to some problems with view. The recommended approach is to add fragments into FrameLayout as described in docs
Also you may want to move everything outside view used for fragments
I have rewritten your layout following recommended guidelines in the docs. P.S I haven't tested how it displayed.. you may have to tweak some layout params.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--
Layout for fragments
-->
<FrameLayout
android:id="#+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_home">
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" android:orientation="horizontal"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
Also You defined multiple activities in your layout like tools:context=".MainActivity" and tools:context=".HomeActivity" I guess it's just unedited copy paste, but may lead some issues as well.
Hope you find it useful :)
In your MainActivity.java add this:
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
#Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
Than in Fragment.java implements class like this:
implements MainActivity.OnBackPressedListener
And implements method:
#Override
public void doBack() {
Intent yourMainActivity = new Intent(getActivity(), MainActivity.class);
startActivity(yourMainActivity);
}
Rubin Nellikunnathu. I had the same issue. Make replacing of your NavigationView fragments in FrameLayout, not RelativeLayout. So you always would have TabLayout and ViewPager loaded.
Place it in mainactivity_layout.xml or in app_bar_home.xml (I do not see your full code, so you try these combinations).
mainactivity_layout.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:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/mainlayout"
tools:showIn="#layout/app_bar_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
// Replace NavigationView fragments in this FrameLayout
<FrameLayout
android:id="#+id/flForReplace"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FrameLayout" />
</RelativeLayout>
and your code should be
fragmentTransaction.replace(R.id.flForReplace, fragment);
also replace fragmentTransaction.addToBackStack(null).commit(); with fragmentTransaction.commit(); as ρяσѕρєя K suggested.