I'm sorry I am not fluent in English.
I wanna change the starting fragment in tab layout.
There is a value from another activity that gave with intent.
so I just want to start tab layout's fragment with my selection.
This is main activity's onCreate()
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
And this is the code of changing in fragment
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
return new TotalFragment();
case 1:
return new StatsFragment();
case 2:
return new FeedbackFragment();
case 3:
return new ManageFragment();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "TOTAL";
case 1:
return "STATS";
case 2:
return "FEEDBACK";
case 3:
return "MANAGE";
}
return null;
}
}
}
Jisu Lee, we can set the starting tab in tab layout with the help of setCurrentItem() to viewpager.
We can set it by two types :
Example :
1.Simple setting tab:
Explation : Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.
viewPager.setCurrentItem(1);
2.For enableing smoothScroll :
Secand parameter "True" to smoothly scroll to the new item, "false" to transition immediately
viewPager.setCurrentItem(1, true);
Or for getting the CurrentItem we have : viewPager.getCurrentItem();
It will return the starting tab index (int).
mViewPager.setCurrentItem({index you want}, true);
Related
I am using two fragments inside viewpager. In the second fragment, I play a video from url using exoplayer. My problem is that when the activity is launch, the video is loaded automatically because all fragments are automatically created by viewpager. How to create one frament at a time so that the second fragment can play the video only if it is visible to the user (by swipping or tapping the tab).
The viewpager adapter
class ViewPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle;
public ViewPagerAdapter(FragmentManager manager, Bundle bundle) {
super(manager);
this.bundle = bundle;
}
#Override
public Fragment getItem(int position) {
Log.d("getItem", position + "");
switch (position) {
case 0:
IngredientListFragment ingredientListFragment = new IngredientListFragment();
ingredientListFragment.setArguments(bundle);
return ingredientListFragment;
case 1:
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(bundle);
return stepsListFragment;
default:
IngredientListFragment ing = new IngredientListFragment();
ing.setArguments(bundle);
return ing;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Ingredients";
case 1:
return "Steps";
default:
return "Ingredients";
}
}
}
Inside the activity
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), bundle);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
Please Help.
you do not need to create fragment one at a time:
use this code in second fragment to run exoplayer when user open that fragment:
private boolean _hasLoadedOnce = false; // your boolean field
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
if (isFragmentVisible_ && !_hasLoadedOnce) {
// move exoplayer code here so this code run only when user select this fragment
_hasLoadedOnce = true;
}
}
}
One more thing, you have to put this line after creating viewpager:
in your case after
tabLayout.setupWithViewPager(viewPager);
viewPager.setOffscreenPageLimit(1);
I have a TabLayout with 3 tab.They are a fragment.
Test.java->PagerAdapter.java->TabFragment1+TabFragment2+TabFragment3
I want to call TabFragment1.helloworld() function. How can i call this function? Thanks.
Test.java created 3 tabs in below
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("tab1"));
tabLayout.addTab(tabLayout.newTab().setText("tab2"));
tabLayout.addTab(tabLayout.newTab().setText("tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(3);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
PagerAdapter.java
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You can access the desired fragment's method through your PagerAdapter:
((TabFragment1)adapter.getItem(0)).helloworld();
It's a bit trickier than usual with ViewPagers, because you can't use the preferred findFragmentByTag() method. Here's something you could try - it's untested, but should be ok:
Create an interface, which all Fragments in your ViewPager implement:
public interface ViewPagerFragmentBase {
void callCommonMethod(int code);
}
Implement it in all your ViewPager Fragments:
public FragmentOne implements ViewPagerFragmentBase {
#Override
public void callCommonMethod(int code) {
if (code == 1) {
//Run code in this Fragment
}
}
public FragmentTwo implements ViewPagerFragmentBase {
#Override
public void callCommonMethod(int code) {
if (code == 2) {
//Run code in this Fragment
}
}
Inside your Activity class, grab all Fragments currently in your Adapter, then cycle through each one, calling the callCommonMethod() along with a code which indicates the Fragment you are trying to reach:
public class MainActivity extends AppCompatActivity {
private void callCommonMethodInFragments(int code) {
for (int i = 0; i < viewPagerAdapter.getCount(); i++) {
((ViewPagerFragmentBase)viewPagerAdapter.getItem(i)).callCommonMethod(code);
}
}
//To call it...
callCommonMethodInFragments(1); //This will run the method in FragmentOne only
}
If the code matches the one in the Fragment you are trying to reach, then the method will run.
Something else you could also try though is an EventBus - this would allow you to achieve your goal more directly, and with less typing: https://github.com/greenrobot/EventBus
To call fragment method from parent activity:
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.callFunction();
I had the same issue, and this worked for me:
You have to add the fragments via your adapter and then you can access the fragment functions:
myViewPager = (ViewPager) findViewById(R.id.viewpager);
MyAdapterClass adapter = new MyAdapterClass(getSupportFragmentManager());
adapter.addFragment(new TabOneFragment(), "");
adapter.addFragment(new TabTwoFragment(), "");
adapter.addFragment(new TabThreeFragment(), "");
myViewPager.setAdapter(adapter);
myTabLayout = (TabLayout) findViewById(R.id.tab_layout);
myTabLayout.setupWithViewPager(myViewPager);
// to access fragment functions:
TabOneFragment tabOneFragment = (TabOneFragment) adapter.getItem(0);
tabOneFragment.functionWhatSoEver();
I have the below code in my app.
From my understanding I expect that after Main activity is loaded getItem from Tab Adapter should be called with index: 1 as it is set as tab-1 .setTabListener(this), 1,true);
But instead of it getItem gets called twice first with index: 0 and then index: 1. Why is that can anyone explain?
//Main activity code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
…
// Tabs Initilization
viewPager = (ViewPager) findViewById(R.id.TabHandler);
actionBar = getActionBar();
mAdapter = new TabsAdapter(getSupportFragmentManager());
actionBar.addTab(actionBar.newTab().setText(tabs[0])
.setTabListener(this), 0, false);
actionBar.addTab(actionBar.newTab().setText(tabs[1])
.setTabListener(this), 1,true);
actionBar.addTab(actionBar.newTab().setText(tabs[2])
.setTabListener(this), 2, false);
}
//And this inside the `Tab Adapter`
public class TabsAdapter extends FragmentPagerAdapter {
public TabsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new ZeroViewFragment();
case 1:
return new OneViewFragment();
case 2:
return new TwoViewFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
This is beacause the ViewPager loads not only the visible fragment but the left and right fragments too. So in your case the visible fragment is #0, there is not left fragment and the right fragment is #1. The result is that fragments #0 and #1 are loaded. This behavior is implemented for performance reasons because this way the ViewPager has the next fragment prepared and ready to be shown and there will be no lag when swiping between pages.
i want to set different pages for ViewPager from class. for example:
i have 4 activity A + B + C and D.
A include my ViewPager.
B +C + D are different pages that must be shown in ViewPager.(each of them have different contex)
my question is that, how can i recognize these pages into ViewPager?
thanks
You can add but better way is that you will create a activity and your four activity should be child fragment of the same .
In short your all activity should be fragments jst load the fregment when you swipe viewpage indicater
sample code for adapter
//User adapter according condition
final FragmentPagerAdapter adapter = new FragmentChildPageAdapter(getChildFragmentManager());
//final FragmentPagerAdapter adapter = new FragmentChildPageAdapter(getActivity().getSupportFragmentManager()));
final ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
final TabPageIndicator indicator = (TabPageIndicator) v.findViewById(R.id.indicator);
indicator.setViewPager(pager);
//Adapter
class FragmentChildPageAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public FragmentChildPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
//first fregment
break;
case 1:
//Second fregment
break;
case 2:
//third fragment
break;
case 3:
//Forth fragment
break;
}
return fragment;
}
#SuppressLint("DefaultLocale")
/*#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}*/
#Override
public int getCount() {
//return CONTENT.length;
return CONTENT.size();
}
#Override
public int getIconResId(int position) {
return (Integer) Icon.get(position % CONTENT.size());
}
}
I have activity and 3 fragments. I use PagerSlidingTabStrip for suport tabs. Adapter:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
...
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
}
return null;
}
...
}
Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1);
final int pageMargin = (int) applyDimension(COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(listener);
tabs.setTextColor(Color.rgb(255, 255, 255));
tabs.setIndicatorColor(Color.parseColor("#FF96AA39"));
}
When app is loading first time getItem is executed 3 times. What is correct. First fragment is shown. Then after change roration getItem for first fragment is not executed. But when I switch to secons or third one getItem is executed.
Could you help me why getItem is not called for first fragment when screen orientation was changed?