My app has an activity with NavigationView and for different items in the navigation drawer UI is changed by changing the fragment. One such fragment has TabLayout implemented in it.
When the app starts the fragment with TabLayout is loaded and it works fine but when I switch between different items in the navigation drawer and then come back to the item which has the TabLayout, now on swiping the tabs the indicator gets stuck in between tabs and the content on one tab is not even displayed. I have no clue regarding what mistake I might have did. I am using
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
This is the activity which has the NavigationView (activity_start.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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: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_start"
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_start"
app:menu="#menu/start_menu" />
</android.support.v4.widget.DrawerLayout>
This is the code for app_bar_start.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="com.optimilia.readaloud.Start">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
This is the fragment which has the TabLayout (fragment_home.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/activity_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.optimilia.readaloud.HomeFragment">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/custom_tab_layout_height"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
Start.java
public class Start extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private Toolbar toolbar;
private Fragment homeFragment = null;
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
private static final String TAG_HOME = "Home";
private static final String TAG_STORE = "Store";
private static final String TAG_ABOUT = "About";
private static final String TAG_SETTINGS = "Settings";
private static final String TAG_HELP = "Help";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler(this.getMainLooper());
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadFragment(true);
}
}
private void loadFragment(boolean selectNavMenu) {
if (selectNavMenu) {
selectNavMenu();
}
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getFragment() {
switch (navItemIndex) {
case 0:
if (homeFragment == null) {
homeFragment = new HomeFragment();
}
return homeFragment;
case 1:
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
// case 2:
// // movies fragment
// MoviesFragment moviesFragment = new MoviesFragment();
// return moviesFragment;
// case 3:
// // notifications fragment
// NotificationsFragment notificationsFragment = new NotificationsFragment();
// return notificationsFragment;
//
// case 4:
// // settings fragment
// SettingsFragment settingsFragment = new SettingsFragment();
// return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
try {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
catch (Exception ex){}
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_settings:
navItemIndex = 1;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_store:
navItemIndex = 2;
CURRENT_TAG = TAG_STORE;
break;
case R.id.nav_help:
navItemIndex = 3;
CURRENT_TAG = TAG_HELP;
break;
case R.id.nav_about:
navItemIndex = 4;
CURRENT_TAG = TAG_ABOUT;
break;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadFragment(false);
return true;
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
super.onBackPressed();
}
}
HomeFragment.java
public class HomeFragment extends Fragment {
private View currView;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_start,
R.drawable.ic_recent,
R.drawable.ic_reading_list
};
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
currView = inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) currView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) currView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return currView;
}
private void setupViewPager(ViewPager viewPager) {
HomeFragment.ViewPagerAdapter adapter = new HomeFragment.ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new StartFragment(), "Start");
adapter.addFragment(new RecentFragment(), "Recent");
adapter.addFragment(new ReadingListFragment(), "Reading list");
viewPager.setAdapter(adapter);
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
In HomeFragment.java was using getFragmentManager() for ViewPagerAdapter and this was causing the problem. On switching to getChildFragmentManager() it started working perfectly.
Related
I'm trying a fragment navigation drawer, Everything works out fine, but the issue is that I don't want to have a fragment fab on my second fragment.
I really appreciate the help given. Thank you!
I will leave an image of the outcome, So it might be easier to see what I mean
https://imgur.com/a/9U4aGDF
Homepage.java
public class Homepage extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "Homepage";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
mSectionsPageAdapter = new
SectionsPageAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.viewpagers);
setupViewPager(mViewPager);
Log.i("viewpager",mViewPager.toString());
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Toolbar toolbar = findViewById(R.id.toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationview = findViewById(R.id.nav_view);
navigationview.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
navigationview.setCheckedItem(R.id.nav_home);
}
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentPopular(), "Popular");
adapter.addFragment(new FragmentUpcoming(), "Upcoming");
Log.i("adaptaerrrrr",adapter.toString());
viewPager.setAdapter(adapter);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
fragment = new HomeFragment();
break;
case R.id.nav_profile:
fragment = new ProfileFragment();
break;
case R.id.nav_discussion:
fragment = new DiscussionFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
}
super.onBackPressed();
}
}
SectionsPageAdapter.java
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fm, String title) {
mFragmentList.add(fm);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Popular Games";
case 1 :
return "Upcoming Games";
}
return null;
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
activity_homepage.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".Activities.Homepage"
android:background="#000000"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/common_google_signin_btn_text_dark_focused"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark"
android:elevation="4dp"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpagers"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
profileFragment.java
public class ProfileFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
fragment_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFF"
android:clickable="true">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text ="Profile Fragment"
android:textSize="30sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
paste this code before break statement in onNavigationItemSelectedMethod.
you have to attach the fragment to activity.
I'm trying to create an app with navigation drawer and swipe tabs, I want that my swipe tab be always visible like the toolbar. My problem is that the fragment of the swipe bar and the navigation drawer are overlapping.
the image of my app
Could anyone help me please .Here is some peace of my code:
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//=============
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
//=============
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
//=============
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
setUpNavigationView();
}
/***
* Swipe Tabs
*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment(), "ONE");
adapter.addFragment(new AgendaFragment(), "TWO");
adapter.addFragment(new NotificationFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
if(fragment != null){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();}
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
toggleFab();
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// item1
ItemoneFragment itemoneFragment= new ItemoneFragment();
return my_selectionFragment;
case 1:
// item2
ItemtowFragment itemtowFragment = new ItemtowFragment();
return my_activitiesFragment;
case 2:
// item3
ItemthreeFragment itemthreeFragment = new ItemthreeFragment();
return groupFragment;
default:
return null;
}
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_my_activities:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_my_selection:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_group:
navItemIndex = 2;
CURRENT_TAG = TAG_GROUPS;
break;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<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>
app_bar_main.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="com.myApp.activities.MainActivity">
<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/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"></FrameLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:backgroundTint="#color/colorPrimary"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I recently use AHBottomNavigation which have 5 item in bottom bar for example when
I click Home Button it goes to homeActivty which I have 3 tab bar. Everything until here is ok but I realize when we use AHBottomNavigation we should use fragment but
I need to use activities with bars and show AHBottomNavigation in all of them.
I use AHBottomNavigation in all of my activities to handle this and it work's and all of my activities have AHBottomNavigation but when i change activities,
AHBottomNavigation doesnt work as good as normal and it seems that there is a delay in it.
Is there any better solution for this or please inform me if I'm doing something wrong ?
HomeActivity.class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
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);
if (drawer != null) {
drawer.setDrawerListener(toggle);
}
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//[START Tab ]
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
//[*End Tab]
//[Start Bottom N]
bottomNavigation();
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"Tab1");
adapter.addFragment(new Fragment2() , "Tab2");
adapter.addFragment(new Fragment3() , "Tab3");
viewPager.setAdapter(adapter);
}
public void bottomNavigation(){
// [START BottomNavigation]
// TODO add other activitys to setOnTabSelectedListener (HOME , SEARCH , ...)
AHBottomNavigation bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
// Create items
AHBottomNavigationAdapter navigationAdapter = new AHBottomNavigationAdapter(this, R.menu.bottom_navigation);
navigationAdapter.setupWithBottomNavigation(bottomNavigation);
bottomNavigation.setBehaviorTranslationEnabled(true);
bottomNavigation.setAccentColor(Color.parseColor("#3498db"));
bottomNavigation.setCurrentItem(0);
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
switch (position){
case 0 :
break;
case 1 :
// Add
Intent goToAddStuff = new Intent(HomeActivity.this , AddStuffActivity.class);
startActivity(goToAddStuff);
finish();
break;
case 2 :
// Search
break;
case 3:
// Activity's
//My AONActivity have 2 tab too
Intent goToAON = new Intent(HomeActivity.this , AONActivity.class);
startActivity(goToAON);
finish();
break;
case 4:
//Account
break;
}
return true;
}
});
// [*END BottomNavigation]
}
content_home.xml
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/content_id"
tools:showIn="#layout/activity_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
<FrameLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomBar" />
<include layout="#layout/bottom_navigation" />
</android.support.design.widget.CoordinatorLayout>
bottom_navigation.xml
<com.aurelhubert.ahbottomnavigation.AHBottomNavigation
android:id="#+id/bottom_navigation"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_gravity="bottom">
</com.aurelhubert.ahbottomnavigation.AHBottomNavigation>
I also use AHBottomNavigation but you need due to Google Material Design you need to use Fragments, otherwise you implement it incorrect.
Here how it should be :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="#+id/framelayout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.aurelhubert.ahbottomnavigation.AHBottomNavigation
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
This is some code just to show how is better to work with fragments if you have no idea, just I do not know your background and maybe you do not use it because you feel confused with this.
#Override
public void onTabSelected(int position, boolean wasSelected) {
Log.d(TAG, "Position " + position + " was selected" + wasSelected);
if(!wasSelected) {
getSupportFragmentManager()
.beginTransaction()
.replace(FRAME_LAYOUT,
createFragment(position),
createItemDescription(position))
.addToBackStack(null)
.commit();
}
}
private void createBottomNavigationMenu(int defaultCurrentItem){
for(int i = 0; i<5; i++){
// Create bottom navigation item
AHBottomNavigationItem item =
new AHBottomNavigationItem(createItemDescription(i),
createPicture(i));
// Add bottom navigation item
mBottomNavigation.addItem(item);
}
// Set current item programmatically
mBottomNavigation.setCurrentItem(defaultCurrentItem, true);
// Set background color
mBottomNavigation.setDefaultBackgroundColor(Color.parseColor("#56ABF8"));
// Disable the translation inside the CoordinatorLayout
mBottomNavigation.setBehaviorTranslationEnabled(false);
// Set listener
mBottomNavigation.setOnTabSelectedListener(this);
}
// Factory-method patterns
private Fragment createFragment(int position){
switch (position) {
case 1:
return new SettingsFragment_();
case 2:
return new StatisticsFragment_();
case 3:
return new MainFragment_();
case 4:
return new ForthFragment_();
case 5:
return new ReminderFragment_();
}
throw new IllegalArgumentException();
}
private String createItemDescription(int position){
switch (position){
case 1:
return BOT_NAV_ITEM_SETTINGS;
case 2:
return BOT_NAV_ITEM_STATISTICS;
case 3:
return BOT_NAV_ITEM_MAIN;
case 4:
return BOT_NAV_ITEM_FORTH;
case 5:
return BOT_NAV_ITEM_REMINDERS;
}
throw new IllegalArgumentException();
}
private int createPicture(int position){
switch (position){
case 1:
return R.mipmap.ic_settings;
case 2:
return R.mipmap.ic_statistics;
case 3:
return R.mipmap.ic_water;
case 4:
return R.mipmap.ic_launcher;
case 5:
return R.mipmap.ic_reminders;
}
throw new IllegalArgumentException();
}
I found the Solution :
I create HomeFragment which extent fragment like this :
HomeFragment.class
public class HomeFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
private static int currentItem = 0;
AdapterFragment adapter;
public static HomeFragment newInstance(int someInt) {
HomeFragment frag = new HomeFragment();
Bundle args = new Bundle();
args.putInt("tab", someInt);
frag.setArguments(args);
return frag;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentItem", viewPager.getCurrentItem());
}
public static HomeFragment newInstance() {
HomeFragment frag = new HomeFragment();
return frag;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter= new AdapterFragment(getChildFragmentManager());
currentItem=getArguments() != null ? getArguments().getInt("tab") : 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View rootView = inflater.inflate(R.layout.fragment_home,container,false);
tabLayout = (TabLayout) rootView.findViewById(R.id.tablayout);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
/**
*Set an Adapter for the View Pager
*/
if (adapter==null) adapter=new AdapterFragment(getChildFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem( currentItem);
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return rootView;
}
public class AdapterFragment extends FragmentPagerAdapter {
public AdapterFragment(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new Tab1Fragment();
case 1 : return new Tab2Fragment();
case 2 : return new Tab3Fragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Tab1";
case 1 :
return "Tab2";
case 2 :
return "Tab3";
}
return null;
}
}
And in my
MainActivity
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
switch (position){
case 0 :
// Home
HomeFragment homeFragment = new HomeFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_id, homeFragment)
.commit();
break;
case 1:
break;
}
return true;
}
});
I hope this will help you
Actually i new in Android and got stuck in Navigation Drawer..
i have successfully designed material designed navigation drawer and their menu items .
But when i clicked on that menu it open a independent fragment while i want it to open it in particular tabs inside Tab Layout.
i have made separate Tab layout with custom Adapter. mytablayout .xml file is as
<?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"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
app:elevation="0dp"
android:background="#6ec6c5"
app:tabIndicatorColor="#000000"
app:tabSelectedTextColor="#color/textColor"
app:tabTextColor="#A8DCDC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
my Tabfragment class are there:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.fragment_tab, null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager(),int_items ));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
}
MyAdapter is :
public class MyAdapter extends FragmentPagerAdapter {
int int_items;
public MyAdapter(FragmentManager fm,int int_items) {
super(fm);
this.int_items = int_items;
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new ProductFragment();
case 1 : return new ProductFragment();
case 2 : return new ProductFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "PRODUCTS";
case 1 :
return "FEATURED";
case 2 :
return "FAVOURITES";
}
return null;
}
}
My SplitviewActivity is shown like this:
public class SplitViewActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView navigationView;
FragmentManager mFragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_split_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new TabFragment()).commit();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.navigation_item_products:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new TabFragment()).commit();
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new AttachmentFragment());
break;
case R.id.navigation_item_new_Releases:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new ProductFragment()).commit();
/* FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container,new ProductFragment()).commit();*/
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new ImageFragment());
break;
case R.id.navigation_item_favorites:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new TabFragment()).commit();
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new MyLocationFragment());
break;
case R.id.navigation_item_about_us:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new MyLocationFragment());
break;
case R.id.navigation_item_notification:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new MyLocationFragment());
break;
case R.id.navigation_sub_item_01:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.navigation_sub_item_02:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 02 Clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
#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_splash_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
my navigation menu item.xml file are as :
<?xml version="1.0" encoding="utf-8"?>
<group android:checkableBehavior="single">
<item
android:id="#+id/navigation_item_products"
android:checked="true"
android:title="Products" />
<item
android:id="#+id/navigation_item_new_Releases"
android:title="New Releases" />
<item
android:id="#+id/navigation_item_favorites"
android:title="favorites" />
<item
android:id="#+id/navigation_item_about_us"
android:title="About Us" />
<item
android:id="#+id/navigation_item_notification"
android:title="Notifications" />
</group>
<item android:title="">
<menu>
<item
android:id="#+id/navigation_sub_item_01"
android:title="Configure" />
<item
android:id="#+id/navigation_sub_item_02"
android:title="Logout" />
</menu>
</item>
Everything is work fine except.All three tabs has been Shown.navigation drawer also work well.
Only thing that i couldn't understand that how can i open a fragment in tab on click of navigation menuitems.At present when i click on menu item,it open an independent fragment not in tab.How can i achieve this ..Any help would be Appreciated in advanced..
just check on drawer onClick the clicked position and check against each viewpager tabs which tab is what u want and use Viewpager.setCurrentItem(posiition)
to navigate to that tab.
public void setStartTab(String topTab) {
LocalLog.e("TOPTAB",topTab+"");
if(topTab==null){
mViewPager.setCurrentItem(0);
}else{
for(int i=0;i<mTabs.size();i++){
LocalLog.e("TOPTAB",mTabs.get(i).name);
if(mTabs.get(i).name.equalsIgnoreCase(topTab)){
LocalLog.e("TOPTAB",i+"true");
mViewPager.setCurrentItem(i);
}
}
}
}
activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
its works for me
I have written a simple code with navigation drawer and 3 fixed tabs but i facing these two bugs
1> Even when the navigation drawer is open and when i click on it... The tabs which are present at the same spot hidden behind the navigation drawer get clicked as well.
2> When i click the items on navigation drawer... the action get performed but the fragment is not replaced or more precisely hidden by the viewpager.
Here are the codes..
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOne(), getString(R.string.tabOne));
adapter.addFragment(new TabTwo(), getString(R.string.tabTwo));
adapter.addFragment(new TabThree(), getString(R.string.tabThree));
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
ActivityMain.xml
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.coastallabs.chat.devchat.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
In your fragment_navigation_drawer.xml:
set rootview clickable = true.