android navigation drawer item click not working [duplicate] - android

This question already has answers here:
OnClickListener not responding
(2 answers)
RecyclerView inside DrawerLayout within LinearLayout not scrollable/clickable
(1 answer)
Closed 5 years ago.
I'm using MaterialTabHost and NavigationView when i click on navigation drawer item but not working
NavigationView im using example code
Anyone help me fix
My code here
[enter image description here][1]
I think i wrong in function replace frament
MainActivity.java
public class MainActivity extends ActionBarActivity implements MaterialTabListener {
private String TAG = MainActivity.class.getSimpleName();
MaterialTabHost tabHost;
ViewPager pager;
ViewPagerAdapter adapter;
private String[] tabs = {"Home","Category","Favourite"};
Toolbar toolbar;
String strMessage;
private AdView mAdView;
private InterstitialAd mInterstitial;
private String name, link;
private ProgressDialog pDialog;
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private FloatingActionButton fab;
// 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";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) this.findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
this.setSupportActionBar(toolbar);
tabHost = (MaterialTabHost) this.findViewById(R.id.tabHost);
pager = (ViewPager) this.findViewById(R.id.pager );
adapter = new ViewPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
tabHost.setSelectedNavigationItem(position);
}
});
for(String tab_name:tabs)
{
tabHost.addTab(
tabHost.newTab()
.setText(tab_name)
.setTabListener(MainActivity.this)
);
}
//navigation
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
//end navigation
}
//navigation
private void loadNavHeader() {
// name, website
txtName.setText("Ravi Tamada");
txtWebsite.setText("www.androidhive.info");
// loading header background image
Glide.with(this).load(urlNavHeaderBg)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavHeaderBg);
// Loading profile image
Glide.with(this).load(urlProfileImg)
.crossFade()
.thumbnail(0.5f)
.bitmapTransform(new CircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfile);
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, HomeFragment.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, HomeFragment.class));
drawer.closeDrawers();
return true;
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();
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
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
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.ad_linear, 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
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
case 2:
// movies fragment
CategoryFragment moviesFragment = new CategoryFragment();
return moviesFragment;
case 3:
// notifications fragment
CategoryFragment notificationsFragment = new CategoryFragment();
return notificationsFragment;
case 4:
// settings fragment
CategoryFragment settingsFragment = new CategoryFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
//end navigation
#Override
public void onTabSelected(MaterialTab tab) {
// TODO Auto-generated method stub
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(MaterialTab tab) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(MaterialTab tab) {
// TODO Auto-generated method stub
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int num) {
switch (num) {
case 0:
return new HomeFragmentCheck();
case 1:
return new CategoryFragmentCheck();
case 2:
return new FavouriteFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.about:
Intent intab=new Intent(MainActivity.this,AboutActivity.class);
startActivity(intab);
break;
case R.id.update:
showPU();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}
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" />
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/m_tab_clr"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<it.neokree.materialtabs.MaterialTabHost
android:id="#+id/tabHost"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_below="#+id/toolbar"
app:accentColor="#color/m_tab_select_accent_clr"
app:primaryColor="#color/m_tab_clr" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/ad_linear"
android:layout_below="#+id/tabHost" />
<LinearLayout
android:id="#+id/ad_linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
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.app.apk.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/AppTheme.AppBarOverlay">
</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"></FrameLayout>
</android.support.design.widget.CoordinatorLayout>

Related

In Slide Menu Control With Tab View Giving Tabs Empty In Android Studio

Actually, I'm working one app that app has side menu drawer and in a home page, tab view is there.
In that menu have 5 fragments let's say
HomeFragment
PhotosFragment
NotificationsFragment
These are in menu and in home fragment, two tabs are like recent tab and all tab
so now I'm going to say what happened, menu control and tab control working without bug but whenever app starting time only.
I mean see now app started by default it shows home fragment, in that home fragment I said know 2 tabs are there.So those are working but now coming to point what was the bug.
If I select another menu item to let's say Photos Fragment then after again I select Home Fragment those tabs are not showing.
I mean whenever app starts the first time its showing tabs after that not showing.
Why its coming like this really I don't know I checked lot ways.
this is my code
main_activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// name, website
txtName.setText("Dummy");
txtWebsite.setText("www.dumnypaul.blogspot.in");
// loading header background image
Glide.with(this).load(urlNavHeaderBg)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavHeaderBg);
// Loading profile image
Glide.with(this).load(urlProfileImg)
.crossFade()
.thumbnail(0.5f)
.bitmapTransform(new CircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfile);
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// selecting appropriate nav menu item
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();
// show or hide the fab button
toggleFab();
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
// This effect can be seen in Gmail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
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:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
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() {
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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
drawer.closeDrawers();
return true;
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 don't 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 don't want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.addDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// show menu only when home fragment is selected
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
// when fragment is notifications, load the menu created for notifications
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, 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();
//no inspection SimplifiableIfStatement
if (id == R.id.action_logout) {
Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
// user is in notifications fragment
// and selected 'Mark all as Read'
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
}
// user is in notifications fragment
// and selected 'Clear All'
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
My HomeFragment Code
public class HomeFragment extends Fragment {
View view;
private TabLayout tabLayout;
private ViewPager viewPager;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new MoviesFragment(), "ONE");
adapter.addFragment(new PhotosFragment(), "TWO");
adapter.addFragment(new SettingsFragment(), "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);
}
}
}
My Home Fragment XML Code
<FrameLayout
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.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.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"/>
Can anybody solve me this bug
Thanks in advance

Is There any Possible to Achieve Use SlideMenu With TabView In Android Studio

Actually i'm designing one app now.
Slide menu control, this menu have 5 categories like 5 fragments.
Each fragment have different different datas.I implemented slide menu also working perfectly.
Here first fragment is home fragment,In that i need to use tab swipe view control i mean two tabs will be there like tab names recent and all tabs.
So when i press recent tab needs to show something and when i press all tab needs to show something.
But here i don't know how to use i researched for lot but i didn't get those.
What i exactly need is in slide menu home fragment i need tab based fragment
For your reference this screen shot
I need those codes please.And let me know is it possible or not.
Thanks in advance
this is my home fragment
public class HomeFragment extends Fragment {
View view;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new MoviesFragment(), "ONE");
adapter.addFragment(new PhotosFragment(), "TWO");
adapter.addFragment(new SettingsFragment(), "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);
}
}
These Fragments are for tab
adapter.addFragment(new MoviesFragment(), "ONE");
adapter.addFragment(new PhotosFragment(), "TWO");
adapter.addFragment(new SettingsFragment(), "THREE");
all are just empty fragments..thanks in advance
this is my main activity
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private Toolbar toolbar;
private FloatingActionButton fab;
// urls to load navigation header background image
// and profile image
private static final String urlNavHeaderBg = "http://api.androidhive.info/images/nav-menu-header-bg.jpg";
private static final String urlProfileImg = "https://lh3.googleusercontent.com/eCtE_G34M9ygdkmOpYvCag1vBARCmZwnVS6rS5t4JLzJ6QgQSBquM0nuTsCpLhYbKljoyS-txg";
// 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_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// name, website
txtName.setText("Ravi Tamada");
txtWebsite.setText("www.androidhive.info");
// loading header background image
Glide.with(this).load(urlNavHeaderBg)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavHeaderBg);
// Loading profile image
Glide.with(this).load(urlProfileImg)
.crossFade()
.thumbnail(0.5f)
.bitmapTransform(new CircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfile);
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// selecting appropriate nav menu item
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();
// show or hide the fab button
toggleFab();
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
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
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:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
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() {
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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
drawer.closeDrawers();
return true;
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();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// show menu only when home fragment is selected
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
// when fragment is notifications, load the menu created for notifications
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, 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_logout) {
Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
// user is in notifications fragment
// and selected 'Mark all as Read'
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
}
// user is in notifications fragment
// and selected 'Clear All'
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}

java.lang.ArrayIndexOutOfBoundsException: length=5; index=5? I want to add fragment in navigation drawer

I am getting error,When I click LoginFragment.When I remove loginFragment.
It works fine.
How to change length for adding more fragment.I am not able to add new fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG_HOME = "home";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
private static final String TAG_LOGIN = "login";
public static int navItemIndex = 0;
public static String CURRENT_TAG = TAG_HOME;
private NavigationView navigationView;
private DrawerLayout drawer;
private Toolbar toolbar;
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
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();
// show or hide the fab button
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
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);
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
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;
case 5:
// ic_login_black_24dp fragment
LoginFragment loginFragment = new LoginFragment();
return loginFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_login:
navItemIndex = 5;
CURRENT_TAG = TAG_LOGIN;
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();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
}
activity_main_drawer.xml
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/nav_home" />
<item
android:id="#+id/nav_photos"
android:icon="#drawable/ic_photo_library_black_24dp"
android:title="#string/nav_photos" />
<item
android:id="#+id/nav_movies"
android:icon="#drawable/ic_local_movies_black_24dp"
android:title="#string/nav_movies" />
<item
android:id="#+id/nav_notifications"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/nav_notifications" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="#string/nav_settings" />
<item
android:id="#+id/nav_login"
android:icon="#drawable/ic_login_black_24dp"
android:title="login" />
</group>
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
<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="info.androidhive.navigationdrawer.activity.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.AppBarLayout>
<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.CoordinatorLayout>
nav_header_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/view_container"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:gravity="bottom"
android:orientation="vertical"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/img_header_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#mipmap/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<ImageView
android:id="#+id/img_profile"
android:layout_width="#dimen/profile_width"
android:layout_height="#dimen/profile_height"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#android:drawable/sym_def_app_icon" />
<TextView
android:id="#+id/namea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/website"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5?
Looks like Exception happens when you call:
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
navItemIndex has range from 0 to 5 (a.e. length 6) when activityTitles has only 5 items
Solution:
Set 6 items for activityTitles

Fragment doesn't change after item click Navigation Drawer

I'm building an app which contains a NavigationDrawer to navigate between Fragments.
For some reason, when pressing on any item in the Navigation Drawer the item just marks itself and doesn't change the fragment (tried debug but the item clicks doesn't calls the functions)
The fragment is not loading in first click..i have to press twice to reload the fragment
Main Activity:
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtCity;
private Toolbar toolbar;
private FloatingActionButton fab;
// urls to load user profile & background
private static final String urlNavHeaderBg = "";
private static final String urlProfileImg = "";
//current menu pressed
public static int navItemIndex = 0;
//tags for fragments
private static final String TAG_HOME = "home";
private static final String TAG_PROFILE = "profile";
private static final String TAG_RATEUS = "rate us";
private static final String TAG_SCORE = "rate score";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
private String[] activityTitles;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
//nav view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtCity = (TextView) navHeader.findViewById(R.id.city);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
//load the toolbar titles
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Make action here", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
//load the navigator header data
loadNavHeader();
//initialize nav menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadNavHeader() {
txtName.setText("My Name");
txtCity.setText("Somewhere, Europe");
Glide.with(this).load(urlNavHeaderBg).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imgNavHeaderBg);
Glide.with(this).load(urlProfileImg).thumbnail(0.5f).bitmapTransform(new CircleTransform(this)).diskCacheStrategy(DiskCacheStrategy.ALL).into(imgProfile);
navigationView.getMenu().getItem(4).setActionView(R.layout.menu_dot);
}
private void loadHomeFragment() {
selectNavMenu();
setToolBarTitle();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
Fragment fragment = getHomeFragment();
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 != null) {
mHandler.post(mPendingRunnable);
}
toggleFab();
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
ProfileFragment profileFragment = new ProfileFragment();
return profileFragment;
case 2:
RateusFragment rateusFragment = new RateusFragment();
return rateusFragment;
case 3:
ScoreFragment scoreFragment = new ScoreFragment();
return scoreFragment;
case 4:
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 5:
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolBarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setCheckable(true);
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_profile:
navItemIndex = 1;
CURRENT_TAG = TAG_PROFILE;
break;
case R.id.nav_rateus:
navItemIndex = 2;
CURRENT_TAG = TAG_RATEUS;
break;
case R.id.nav_score:
navItemIndex = 3;
CURRENT_TAG = TAG_SCORE;
break;
case R.id.nav_notifications:
navItemIndex = 4;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 5;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_terms:
startActivity(new Intent(MainActivity.this, TermsActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
//when nav closed this will triggered - leaving blank so nothing won't happen
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
//when nav opened this will triggered - leaving blank so nothing won't happen
super.onDrawerOpened(drawerView);
}
};
drawer.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
if (shouldLoadHomeFragOnBackPress) {
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
if (navItemIndex == 4) {
getMenuInflater().inflate(R.menu.notifications, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.action_mark_all_read) {
Toast.makeText(getApplicationContext(), "All marked as read!", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_clear_notifications) {
Toast.makeText(getApplicationContext(), "All Cleared!", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
tools:context=".activity.MainActivity">
<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" />
There are couple of problems with the code:
Make sure u add break in switch:
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
break; //add break
case R.id.nav_terms:
startActivity(new Intent(MainActivity.this, TermsActivity.class));
drawer.closeDrawers();
break;
default:
navItemIndex = 0;
break;
Also your fragment not loading as you are not calling the function properly:
in your Switch case:
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
Fragment fragment = getHomeFragment(); //get fragment based on index
ReplaceFragment(fragment); //now replace them and load new one
drawer.closeDrawers();
break;
in ReplaceFragment method write:
public void ReplaceFragment(Fragment r_fragment) {
if (r_fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, r_fragment).commit();
} else {
// error in creating fragment
}
}
Also overWrite following methods:
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
drawerView.bringToFront(); //add this two lines
drawerView.requestLayout();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}

Add Navigation Drawer with Tabs in Fragment

Acualy i created a navigation Drawer activity and this activiy works perfectly but i want to add the first item of Navigaion Drawer with tab layout and the remaining item with the fragments(which i already done) so please hep me how can i do this:
NavigationDrawer Activity:
public class NotificationDrawer extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private Toolbar toolbar;
private static final String urlProfileImg = "http://www.google/images.com;
public static int navItemIndex = 0;
// tags used to attach the fragments
private static final String TAG_HOME = "home";
private static final String TAG_VEHICLE = "vehicle";
private static final String TAG_ADDRESS= "address";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_navigation);
toolbar = (Toolbar) findViewById(R.id.toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_sort_white_24dp);
setSupportActionBar(toolbar);
/* getSupportActionBar().setHomeButtonEnabled( true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_sort_white_24dp);*/
toolbar.setNavigationIcon(R.drawable.ic_sort_white_24dp);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.website);
imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
// loadNavHeader();
txtName.setText("Techiee");
txtWebsite.setText("www.techiee.com");
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
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();
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:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// registered_vehicle
Registered_Vehicle registeredVehicle = new Registered_Vehicle();
return registeredVehicle;
case 2:
// registeredAddress fragment
RegisteredAddress registeredAddress = new RegisteredAddress();
return registeredAddress;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// navigationView.setItemIconTintList(null);
//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.registered_vehi:
navItemIndex = 1;
CURRENT_TAG = TAG_VEHICLE;
break;
case R.id.registered_address:
navItemIndex = 2;
CURRENT_TAG = TAG_ADDRESS;
break;
drawer.closeDrawers();
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.drawer_open, R.string.drawer_close) {
#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();
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
toolbar.setNavigationIcon(R.drawable.ic_sort_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawer.openDrawer(GravityCompat.START);
}
});
}
drawer_navigation.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:itemIconTint="#color/buttonbackground"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout
>
To add the Tablayout with NavigationDrawer :
1.create a new File “TabFragment.java” to inflate & code TabLayout and viewPager elements.
2.For viewPager to display content it requires a Adapter . use a FragmentPagerAdapter which is used to inflate tab specific fragments.
3.The FragmentPagerAdapter overrides three main methods :
a) getCount() : It returns the total number of tabs to be bind with the view pager.
b) getItem(int position) : It returns the tab-specific fragment wrt to its position.
c) getPageTitle(int position)` : It returns name of the title according to the position
4.At the end , attach your ViewPager with the TabLayout with the setupWithViewPager(viewPager) method of the TabLayout .
Here is a detail implementation: https://androidbelieve.com/navigation-drawer-with-swipe-tabs-using-design-support-library/
Hope it helps.
As u are using toolbar you can use:
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//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);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.first:
toolbar.setTitle("First Item");
return true;
case R.id.second:
toolbar.setTitle("Second Item");
return true;
}
}
to set title..during click on fragments

Categories

Resources