1

I have four fragments, each of them have a TextView.

  1. I want to start all fragments and setText for the TextView of each fragment (The activity will only show one fragment at a time).

  2. Switch between fragment without deleting it. I've tried to setText but it give null pointer exception if I don't show the fragment.

I use BottomBar to switch between fragments. I'm new with android and my English skill is bad. Thanks :D

Sanjeet
  • 2,385
  • 1
  • 13
  • 22
hungps
  • 389
  • 2
  • 11

2 Answers2

1

You could use a FragmentPagerAdapter.

As described in the documentation (and an example from Google):

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

Beware that depending on how many tabs your bottom bar contains, your activity could be taking a lot of memory ;)

A very complete guide from codepath could also help you a lot:

  • Define Fragments
  • Setup FragmentPagerAdapter
  • Apply the Adapter
  • Selecting or Getting the Page
  • Setup OnPageChangeListener

All of these topics are explained with an example there.

About the BottomBar you have a really good example here on StackOverflow

Hope it helps! =)

Community
  • 1
  • 1
HenriqueMS
  • 3,864
  • 2
  • 30
  • 39
1

Try using a ViewPager and FragmentStatePagerAdapter here

Try below code for changing fragment on button click

 Button buttonNext= (Button)findViewById(R.id.buttonNext);//button in Bottombar
            buttonNext.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    vPager.setCurrentItem(1, true);

                }
            }); 

for more about viewpager

Rissmon Suresh
  • 13,173
  • 5
  • 29
  • 38