Using both NavigationDrawer and Tabs (Android) - android

I'm building an app with some tabs and a NavigationDrawer on the side. My problem is I can't display the content of the fragments from my NavigationDrawer : when I click on it nothing happen, I still see my tabs but no new fragment.
I followed those tutorials, one is for the NavigationDrawer and the other one for the tabs, both work separately.
http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
MainActivity.java (Let me know if you need some more code, I'll edit my post and add it)
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_favorite_white_24dp,
R.drawable.ic_lightbulb_outline_white_24dp,
R.drawable.ic_face_white_24dp
};
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
Log.i("USER ", mAuth.getCurrentUser().getEmail().toString());
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Log.d("ACTION BAR?", actionBar.toString());
actionBar.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);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("TAG", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("TAG", "onAuthStateChanged:signed_out");
}
// ...
}
};
// ...
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
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);
Log.i("DISPLAY VIEW", "HOME FRAGMENT DISPLAYED");
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
Log.i("DISPLAY VIEW", "FRIENDS FRAGMENT DISPLAYED");
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
Log.i("DISPLAY VIEW", "MSG FRAGMENT DISPLAYED");
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
I have the displayView() that should display the correct view from the NavigationDrawer but I also have the tabLayout. When I click on the differents items from the NavigationDrawerI have the title changing in the Toolbar but nothing more.
It is very well explained but I'm probably missing something, I know it's probabably a bit of newbie question but since it's my first Android app I guess I'm sort of one. If anyone could give a look and tell me what I should do to make those 2 work together, would be really helpful to me. Thanks!

Related

BottomNavigationView set optionselected with ViewPager Xamarin

I am building a App Where I use A BottomNavigationView and display the fragments with a ViewPager.
When I push or touch the buttoms of the Bottom Navigation, I dont have problems, the fragment displays correctly in the viewpager.
The problem is that I can slide just the viewPager and when I do it, the bottom navigation does not change to the correct option.
I saw that I need to add ViewPager.IOnPageChangeListener and create three methods for manage the view pager, but I dont now How to set the BottomNavigation item selected when the user slide the viewpager
For example, I touch the buttom 4 of the BottomNavigationBar and I saw Automatically the fragment 4 in the view pager(where I display the text "Fragment4"),,, and then I slide the ViewPager until the Fragment1, but the BottomNavigation is the option4 still selected,, it does not change when I slide the viewpager u.u
I hope you can help me, thanks
public class MainActivity : AppCompatActivity, ViewPager.IOnPageChangeListener
{
private DrawerLayout drawerLayout;
ViewPager viewPager;
BottomNavigationView bottomNavigation;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView (Resource.Layout.Main);
bottomNavigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_navigation);
bottomNavigation.NavigationItemSelected += Navigation_NavigationItemSelected;
SupportToolbar toolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
SupportActionbar actionBar = SupportActionBar;
actionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
actionBar.SetDisplayHomeAsUpEnabled(true);
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawerLayout);
NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
if (navigationView != null)
{
setUpDrawerContent(navigationView);
}
//TabLayout tabs = FindViewById<TabLayout>(Resource.Id.tabs);
viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
setUpViewPager(viewPager);
//tabs.SetupWithViewPager(viewPager);
}
private void Navigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
switch (e.Item.ItemId)
{
case Resource.Id.navigation_myState:
viewPager.SetCurrentItem(0, false);
break;
case Resource.Id.navigation_study:
viewPager.SetCurrentItem(1, false);
break;
case Resource.Id.navigation_flashcards:
viewPager.SetCurrentItem(2, false);
break;
case Resource.Id.navigation_test:
viewPager.SetCurrentItem(3, false); ;
break;
}
}
private void setUpViewPager(ViewPager viewPager)
{
ViewPagerAdapter adapter = new ViewPagerAdapter(SupportFragmentManager);
adapter.AddFragment(new Fragment1(), "Fragment1");
adapter.AddFragment(new Fragment2(), "Fragment2");
adapter.AddFragment(new Fragment3(), "Fragment3");
adapter.AddFragment(new Fragment4(), "Fragment4");
viewPager.Adapter = adapter;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
drawerLayout.OpenDrawer((int)GravityFlags.Left);
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
private void setUpDrawerContent(NavigationView navigationView)
{
navigationView.NavigationItemSelected += (object sender, NavigationView.NavigationItemSelectedEventArgs e) =>
{
e.MenuItem.SetChecked(true);
drawerLayout.CloseDrawers();
};
}
public class ViewPagerAdapter : FragmentPagerAdapter
{
public List<SupportFragment> Fragments { get; set; }
public List<string> FragmentsNames { get; set; }
public ViewPagerAdapter(SupportFragmentManager FragManager) : base (FragManager)
{
Fragments = new List<SupportFragment>();
FragmentsNames = new List<string>();
}
public void AddFragment(SupportFragment fragment, string name)
{
Fragments.Add(fragment);
FragmentsNames.Add(name);
}
public override int Count
{
get
{
return Fragments.Count;
}
}
public override SupportFragment GetItem(int position)
{
return Fragments[position];
}
public override ICharSequence GetPageTitleFormatted(int position)
{
return new Java.Lang.String(FragmentsNames[position]);
}
}
public void OnPageScrollStateChanged(int state)
{
throw new NotImplementedException();
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
throw new NotImplementedException();
}
public void OnPageSelected(int position)
{
//I think that here I need to put something like bottomNavigatin.setItemselecte(position) or (bottomNavigation.something(Resource.Id.navigation_flashcards)
}
}
The trick is to hookup the ViewPager.PageSelected to BottomNavigationView.NavigationItemSelected. Here's how you can do it
void ViewPager_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
var item = _navigationView.Menu.GetItem(e.Position);
_navigationView.SelectedItemId = item.ItemId;
}
void NavigationView_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
_viewPager.SetCurrentItem(e.Item.Order, true);
}
Demo:
Checkout the full implementation in my post here: https://intelliabb.com/2017/12/02/tutorial-bottomnavigationview-and-viewpager-in-xamarin-android/

android material design tabs fragments not showing up

I have followed the Android codelabs example for material design and I can not get my fragments to display the textedit in each layout please help. Here is my MainActivity.java. Any help would be greatly appreciated, I am new at this as you can probably tell.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
//supportActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
// Set behavior of Navigation drawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Set item in checked state
menuItem.setChecked(true);
// TODO: handle navigation
// Closing drawer on item click
mDrawerLayout.closeDrawers();
return true;
}
});
/*
tabs.addTab(tabs.newTab().setText("Dine In"));
tabs.addTab(tabs.newTab().setText("Carry Out"));
tabs.addTab(tabs.newTab().setText("Orders"));
*/
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new DineInFragment(), "Dine In");
adapter.addFragment(new CarryOutFragment(), "Carry Out");
adapter.addFragment(new OrdersFragment(), "Orders");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(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 postion) {
return mFragmentTitleList.get(postion);
}
}

During run time add or remove tabs in Tablayout with Fragmentpageradapter?

I have implemented TablLayout with FragmentPagerAdapter, I would like to add or remove Tabs but I am unsure how to implement this. I have searched for this but couldn't find it all other examples are similar but not the same as I am not using an arraylist and quite get my head around the tutorials.
This is the FragmentPagerAdapter
public class TabPagerAdapter extends FragmentPagerAdapter {
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Fragment tab1 = new Tab1Fragment();
return tab1;
case 1:
Tab2Fragment tab2 = new Tab2Fragment();
return tab2;
case 2:
Tab3Fragment tab3 = new Tab3Fragment();
return tab3;
case 3:
Tab4Fragment tab4 = new Tab4Fragment();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
This is the activity
public class TabLayoutDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout_demo);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1 Item").setIcon(android.R.drawable.ic_dialog_email));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2 Item").setIcon(android.R.drawable.ic_btn_speak_now));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3 Item").setIcon(android.R.drawable.ic_lock_idle_low_battery));
tabLayout.addTab(tabLayout.newTab().setText("Tab 4 Item").setIcon(android.R.drawable.ic_dialog_alert));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout
.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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 onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab_layout_demo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using the support TabLayout and Viewpager , from what I know addition and removal of tab is to be done from the adapter class, so i tried to use this code but I can't figure out what is tablItems here referring to and how to set up this variable or is there any other way to do this ?
public void removeTabPage(int position) {
if (!tabItems.isEmpty() && position<tabItems.size()) {
tabItems.remove(position);
notifyDataSetChanged();
}
}

Android's fragment transition

I have three fragments, F1, F2 and F3.
In the case of F1 to F2 transition and come back to F1, F1's onCreateView() is not called.
But in the case of F1 to F3 transition and come back to F1, F1's onCreateView() is called. That means F1's layout inflater inflated a new layout.
What is the reason there is a difference between F1 to F2 transition and F1 to F3 transition?
My mainactivity is shown below.
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new F1(), "Raw Data");
adapter.addFragment(new F2(), "Grip");
adapter.addFragment(new F3(), "Press");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks
Into Viewpager fragment of previous and next never destrory.
if you are current fragment f2 than can't call onCreateView() method of f1 and f3.
if you go to f3 fragment than f1 id destroy but not destroy f2 fragment thats why call onCreateView() method of f1 .
if you set viewPager.setOffscreenPageLimit(4); than it create one time only.
sorry for my english is poor.

Refresh tableLayout using ViewPager (with Fragments)

I have a little problem
Current situation
I have a ViewPager with 2 Fragments inside.
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
//////////////////////
private void setupViewPager(ViewPager viewPager) {
adapter = new PagerAdapter (getSupportFragmentManager());
adapter.addFragment(new Frag1(), "Frag1");
adapter.addFragment(new Frag2(), "Frag2");
viewPager.setAdapter(adapter);
}
And I put it in my TabLayout
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
It works very well but now I want to change the fragments inside my tabs when I press a button in my navigation drawer.
Here :
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.nav_menu1:
break;
case R.id.nav_menu2:
here for example
break;
case R.id.nav_menu3:
break;
}
return true;
}
});
}
How should I do this?
PS: I tried to add some notifyDataSetChanged() for the adapter.. invalidate() the tabLayout ... I removed the code because I did it wrong.
Here is my PagerAdapter
static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
Solved with FragmentStatePagerAdapter instead of FragmentPagerAdapter.

Categories

Resources