Not able to call TablayoutActivity from AppcombatActivity - android

I want to call my tablayout activity , when user clicked on Item Menu from Action View Item ,
But I am getting error :
06-15 14:17:01.604: E/AndroidRuntime(1365): java.lang.NoClassDefFoundError: Failed resolution of: Linfo/muscle/reboot/activity/Wrk_plan_gain;
Here is my Main activity from where I am calling Tab layout Activity .
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
public MainActivity() {
// Required empty public constructor
}
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
SharedPreferences pref;
String diet_saved;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = this.getPreferences(1);
diet_saved=pref.getString("diettype", "main");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(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);
}
#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.workout_menu) {
startActivity(new Intent(MainActivity.this, Wrk_plan_gain.class));
finish();
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 KnowYourBodyFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new YourResultFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new YourMacroResultFragment();
title = getString(R.string.title_macro);
break;
case 4:
fragment = new DietPlanFragment();
title = getString(R.string.title_Diet);
break;
case 5:
title = getString(R.string.title_Exit);
finish();
break;
default:
}
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);
}
}
}
and I am trying call this Activity
public class Wrk_plan_gain extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
public Wrk_plan_gain() {
// Required empty public constructor
}
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wrk_plan_layout_gain);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Also it will every much help full I f I can call this activity from Nav drawer Item ..
I am not able to get it work , in both cases .

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();
}
}

Hide navigation drawer and tabs when loading the webview in android fragment

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
// Remove the below line after defining your own ad unit ID.
/* private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";*/
boolean doubleBackToExitPressedOnce = false;
//set viewpager adapter
ViewPagerAdapter pagerAdapter;
private ViewPager viewPager;
private DrawerLayout drawer;
private TabLayout tabLayout;
private String[] pageTitle = {"Home","Movies","Songs", "Comedy"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// Load an ad into the AdMob banner view.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
// Toasts the test ad message on the screen. Remove this after defining your own ad unit ID.
// Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
viewPager = (ViewPager) findViewById(R.id.view_pager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
setSupportActionBar(toolbar);
//create default navigation drawer toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//setting Tab layout (number of Tabs = number of ViewPager pages)
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
for (int i = 0; i < 4; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//handling navigation view item event
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
//set viewpager adapter
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
//change Tab selection when swipe ViewPager
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//change ViewPager page when tab selected
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.movies:
viewPager.setCurrentItem(0);
break;
case R.id.comedy:
viewPager.setCurrentItem(1);
break;
case R.id.songs:
viewPager.setCurrentItem(2);
break;
case R.id.animation:
Intent in = new Intent(this, Animation.class);
// intent.putExtra("string", "");
startActivity(in);
break;
case R.id.albums:
Intent intent = new Intent(this, DesActivity.class);
// intent.putExtra("string", "");
startActivity(intent);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
int position = viewPager.getCurrentItem();
Fragment fragment = pagerAdapter.getItem(position);
if (fragment != null) {
switch (position) {
case 0:
if (((Home) fragment).hasBackPage()) return;
break;
case 1:
if (((MoviesActivity) fragment).hasBackPage()) return;
break;
case 2:
if (((SongsActivity) fragment).hasBackPage()) return;
break;
case 3:
if (((ComedyActivity) fragment).hasBackPage()) return;
break;
}
if (position == 0) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Touch again to Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
viewPager.setCurrentItem(0);
}
}
}
}
Initially hide both TabLayout and NavigationDrawer and show when WebView loaded by using below code
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
showViews();
}
});

restore tab state on switching from navigation drawer

I have 4 tabs in Fragment A.The first tab has a listview. I have attached a Navigation drawer switching between other 3 tabs, Fragment B, C and D. Now when I switch from Fragment A to Fragment B and back, the first tab doesn't show the listview. But when I switch from 3rd tab and come back to 1st tab it gets the listview data and loads it. What am I doing wrong? I have attached my MainActivity which has implemented navigation drawer and my HomeFragment which has four tabs.
MainActivity.java
public class MainActivity extends AppCompatActivity implements {
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
// 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);
mDatabase1 = FirebaseDatabase.getInstance().getReference();
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
// 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();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
}
/***
* 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:
case 2:
case 3:
case 4:
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.nav_home:
navItemIndex = 0;
break;
case R.id.nav_live:
navItemIndex = 1;
break;
case R.id.nav_edit:
navItemIndex = 2;
break;
case R.id.nav_competitions:
navItemIndex = 3;
break;
case R.id.nav_settings:
navItemIndex = 4;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, CompetitionActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_report_bug:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, ReportBugActivity.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;
}
}
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}).setNegativeButton("no", null).show();
//System.exit(0);
//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) {
auth = FirebaseAuth.getInstance();
auth.signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private int dpToPx(int dp)
{
float density = getApplication().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
#Override
public void setActionBarTitle(String home) {
}`**
HomeFragment.java
public class HomeFragment extends android.support.v4.app.Fragment {
private AppCompatActivity aca=new AppCompatActivity();
//private class Act extends AppCompatActivity {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
//tabs
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_question_answer_black_24dp,
R.drawable.ic_notifications_black_24dp,
R.drawable.ic_people_black_24dp,
R.drawable.ic_face_black_24dp,
};
private OnFragmentInteractionListener mListener;
private LayoutInflater inflator;
public ViewGroup container;
private Bundle savedInstancesState;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
public HomeFragment() {
// Required empty public constructor
}
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context=getContext();
inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View v=inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
//viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) v.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return v;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
ColorStateList colors;
colors = getResources().getColorStateList(R.color.tab_icon);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
Drawable icon = tab.getIcon();
if (icon != null) {
icon = DrawableCompat.wrap(icon);
DrawableCompat.setTintList(icon, colors);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter((getActivity()).getSupportFragmentManager());
adapter.addFrag();
adapter.addFrag();
adapter.addFrag();
adapter.addFrag();
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<android.support.v4.app.Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
//return mFragmentTitleList.get(position);
return null;
}
}
public void setActionBarTitle(String title) {
aca.getSupportActionBar().setTitle(title);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
void setActionBarTitle(String home);
}
}

NavigationDrawer not show the view

I have a Navigation Drawer with Navigation View, there are four tabs, one of them is a fragment, which includes ViewPager, ie is a host for the other fragments. Everything works fine, but when switched from fragment with ViewPager any other fragment of NavigationDrawer shows nothing. Checked logs, onCreate, onCreateView these fragments are called, but why does not display... Who knows why?
NavigationDrawer
public class NavigationDrawerHost extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
//буду использовать эту активность как хост под все фрагменты, чтобы верно работал мой drawer!
public static String WHERE_FROM = NavigationDrawerHost.class.getSimpleName();
public static Toolbar toolbar;
public static ProgressBar progressBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
private int navItemId;
private static final String NAV_ITEM_ID = "NAV_ITEM_ID";
private TextView userFirstNameTextView, userLastNameTextView;
private ImageView userPhotoImageView;
private VKAccessToken access_token; //токен это информация о правах доступа
private VKApiUser user; //текущий пользователь
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer_host);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find the toolbar view inside the activity layout
toolbar = (Toolbar) findViewById(R.id.toolbar);
// Set a Toolbar to replace the ActionBar.
setSupportActionBar(toolbar);
//setTitle(R.string.drawer_menu_posts);
// load saved navigation state if present
if (null == savedInstanceState) {
navItemId = R.id.posts_fragment;
} else {
navItemId = savedInstanceState.getInt(NAV_ITEM_ID);
}
// Find our drawer view
navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(navItemId).setChecked(true);
// если хотим добавить какие-то элементы в наш header,
// то нужно добавить их в layout, а затем инициализировать нижеприведенным способом
// Inflate the header view at runtime
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
userFirstNameTextView = (TextView) headerLayout.findViewById(R.id.user_first_name);
userLastNameTextView = (TextView) headerLayout.findViewById(R.id.user_last_name);
userPhotoImageView = (ImageView) headerLayout.findViewById(R.id.user_photo);
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
// Tie DrawerLayout events to the ActionBarToggle
drawer.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectItem(navItemId);
}
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(NAV_ITEM_ID, navItemId);
}
// Menu icons are inflated just as they were with actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_exit:
//quitDialog();
VKSdk.logout();
finish();
return true;
default:
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(final int itemId) {
// perform the actual navigation logic, updating the main content fragment etc
// Create a new fragment and specify the planet to show based on position
Fragment fragment = null;
Class fragmentClass = null;
switch (itemId) {
case R.id.posts_fragment:
fragmentClass = PostsFragment.class;
fragment = new PostsFragment();
break;
case R.id.albums_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.friends_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.likes_fragment:
fragmentClass = LikesFragment.class;
fragment = new LikesFragment();
break;
/*default:
fragmentClass = PostsFragment.class;*/
}
/*try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}*/
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
drawer.closeDrawers();
}
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// update highlighted item in the navigation menu
item.setChecked(true);
setTitle(item.getTitle());
navItemId = item.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
drawer.closeDrawer(GravityCompat.START);
selectItem(item.getItemId());
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
quitDialog();
} else {
getSupportFragmentManager().popBackStack();
}
}
private void quitDialog() {
AlertDialog.Builder quitDialog = new AlertDialog.Builder(this);
quitDialog.setTitle("Вы хотите выйти?");
quitDialog.setPositiveButton("Да", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//стираем БД
Delete.tables(PostTable.class, PictureTable.class, PostTableMyLikes.class, PictureTableMyLikes.class);
FlowManager.getDatabase(WallDatabase.DB_NAME).reset(NavigationDrawerHost.this);
FlowManager.getDatabase(WallDatabaseMyLikes.DB_NAME).reset(NavigationDrawerHost.this);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
quitDialog.setNegativeButton("Нет",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
quitDialog.show();
}
}
ViewPager host for fragments, which needs to display through ViewPager
//этот фрагмент является хостом для MyLikesFragment и FriendLikesFragment, так же тут содержатся табы
public class LikesFragment extends Fragment {
public static String WHERE_FROM_FRIENDS_LIKES = LikesFragment.class.getSimpleName() + "_FRIENDSLIKES";
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.likes_fragment, container, false);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Мои лайки"));
tabLayout.addTab(tabLayout.newTab().setText("Лайки друзей"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setAdapter(new LikesPagerAdapter(getChildFragmentManager()));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
public static class LikesPagerAdapter extends FragmentPagerAdapter {
public LikesPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
//сделано так, чтобы передавать те аргументы, от которых будет зависеть функционал фрагмента
#Override
public Fragment getItem(int position) {
return (position == 0) ? new MyLikesPostsFragment() : new PostsFragment();
}
#Override
public CharSequence getPageTitle(int position) {
return (position == 0) ? "Мои лайки" : "Лайки друзей";
}
}
}
P.S. And after going to the same fragment ViewPager select several items in drawer, this should not be
The problem was that I called adapter.notifyDataSetChanged() in the main thread and onPostExecute() in AsyncTask. My carelessness...

Categories

Resources