I have multiple tabs using FragmentPagerAdapter but the ViewPager creates a page before and after my current tab and the OnCreate() method gets called even when I'm not on that tab. It becomes really difficult to run a specific operation on a specific tab rather than executing before visiting the tab. Is there anyway so that I can detect if the user has visited the particular tab from the tab itself?
public class MainActivity extends ActionBarActivity implements ViewPager.OnPageChangeListener {
public static final int TAB_PROFILE = 0;
public static final int TAB_JOBS = 1;
public static final int TAB_GPS = 2;
public static final int TAB_COMMENTS = 3;
public static final int TAB_OTHERS = 4;
Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mPager.setOnPageChangeListener(this);
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setCustomTabView(R.layout.custom_tab_item, R.id.tabText);
mTabs.setDistributeEvenly(true);
mTabs.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
mTabs.setViewPager(mPager);
}
#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;
}
if (id == R.id.action_search) {
startActivity(new Intent(this, subActivity.class));
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d("CURRENT_TAB", "" + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
class MyPagerAdapter extends FragmentPagerAdapter {
//String[] tabsTitle = getResources().getStringArray(R.array.tabs);
int tabIcons[] = {R.drawable.ic_tab_home,
R.drawable.ic_tab_job,
R.drawable.ic_tab_map,
R.drawable.ic_tab_comments,
R.drawable.ic_tab_others};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
//tabsTitle = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Logs.logs("getItem called for " + position);
switch (position) {
case TAB_PROFILE:
fragment = FragmentProfile.newInstance("" + position, "true");
break;
case TAB_JOBS:
fragment = FragmentJobs.newInstance("" + position, "true");
break;
case TAB_GPS:
fragment = FragmentGPS.newInstance("" + position, "true");
break;
case TAB_COMMENTS:
fragment = FragmentComments.newInstance("" + position, "true");
break;
case TAB_OTHERS:
fragment = FragmentOthers.newInstance("" + position, "true");
break;
}
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
Drawable drawable = getResources().getDrawable(tabIcons[position]);
drawable.setBounds(0, 0, 36, 36);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
#Override
public int getCount() {
return 5;
}
}
}
Tab #1
public class FragmentProfile extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_profile, container,false);
return view;
}
}
Okay after searching for a quite long time, I finally figured out that you were calling setOnPageChangeListener() for ViewPager instead of calling setOnPageChangeListener() for SlidingTabLayout
This question was answered here,
onPageScrolled() not being called
What about havong your main fragment implementing ViewPager.OnPageChangeListener , then you may override onPageSelected
Related
I've created Activity to handle ViewPager. At the beginning it was working fine, but then I had to add some more code, to make it refresh my pages while selecting them. I've handled it by calling onResume() method with every page change.
I've optimized my Fragments, cleared unnecessary code (inside onResume()) in each of them, but this give no result. That's how my Activity looks like:
public class MainTabsActivity extends AppCompatActivity implements FullList.OnListFragmentInteractionListener, AcceptedList.OnListFragmentInteractionListener, StartedList.OnFragmentInteractionListener {
private static final int NUM_TABS = 3;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tabs);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
Fragment fragment = ((SectionsPagerAdapter)mViewPager.getAdapter()).getFragment(i);
if (fragment != null) {
Log.e("PAGE SELECTED", " " + i);
tabLayout.getTabAt(i).select();
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
Intent i = getIntent();
int pageNum = i.getIntExtra("pagenumber", 0);
mViewPager.setCurrentItem(pageNum);
tabLayout.getTabAt(pageNum).select();
mViewPager.invalidate();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_tabs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListFragmentInteraction(DummyContent.DummyItem item) {
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentTags = new HashMap<>();
mFragmentManager = fm;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return getString(R.string.tab_text_1);
case 1:
return getString(R.string.tab_text_2);
case 2:
return getString(R.string.tab_text_3);
}
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FullList tab1 = new FullList();
return tab1;
case 1:
AcceptedList tab2 = new AcceptedList();
return tab2;
case 2:
StartedList tab3 = new StartedList();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return NUM_TABS;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null) return null;
return mFragmentManager.findFragmentByTag(tag);
}
}
}
I've added code, to call onResume() method, but funny thing is that the Fragments are loading so long only while I open this Activity from another, but not while scrolling between pages (everything works smoothly then), before changes everything was fine.
Is there any way to make this work faster?
You don't need to write onPageSelected code to change your tab selection.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager); // this will synchronize our tablayout with your viewpager
You should not call onResume directly, this is a system event and a call to this void
is not recommended.
Also, in your case, no need to call mViewPager.invalidate()
Hi i am working in an app, in which:
View pager is there on an activity.
On that view pager i am showing 2 fragments(frag1 and frag2).
on button click on frag1 we have added one more fragment(lets say frag3).
and on back press on frag3 i come back on frag1.
Issue:
the issue is when i come back to frag1 from frag3 on back press, sometimes frag1 is not attached to the activity.
i am not able to figure out how this is happening.
if this is happening then what is the solution so i can stop activity to detach the frag1 or re-initialize the frag1 again.
Please help.
This code may help you
public class PageAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final int[] PAGER = new int[] {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4
};
private int mCount = PAGER.length;
public PagerFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new PagerFragment(PAGER[position]);
}
#Override
public int getIconResId(int index) {
return ICONS[index % PAGER.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
Defining Fragments
public final class PagerFragment extends Fragment {
private static final String KEY_CONTENT = "PagerFragment:Content";
int imageSource;
public PagerFragment(int imageSource) {
this.imageSource = imageSource;
}
public PagerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
imageSource = savedInstanceState.getInt(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.indicatorpage, null);
ImageView image = (ImageView) root.findViewById(R.id.pagerImage);
image.setImageResource(imageSource);
setRetainInstance(true);
return root;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_CONTENT, imageSource);
}
}
MainActivity Class
public class MainActivity extends FragmentActivity {
PagerFragmentAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new PagerFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("selected page is :" + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
CirclePageIndicator mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
mIndicator.setRadius(7 * density);
mIndicator.setPageColor(0x00000000);
mIndicator.setFillColor(0xFFFFFFFF);
mIndicator.setStrokeColor(0xFFFFFFFF);
mIndicator.setStrokeWidth(1 * density);
}
#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);
}
}
i´m using tablayout and i want to update the tab content when user clicks on the tab. basicly i want to do what the tab does when it is created (check what it is in database and put it on my listview).
here is my MainActivity:
public class MainActivity extends AppCompatActivity{
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout;
CharSequence Titles[]={"Participantes","Torneio","Classificação"};
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
// Creating The Toolbar and setting it as the Toolbar for the activity
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorTextIcons));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
adapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
viewPager = null;
}
#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, 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;
}
if (id == R.id.action_info) {
Toast.makeText(getApplicationContext(), "Contacto: Juniortalisson16#gmail.com", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my ViewPageradapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
switch(position) {// if the position is 0 we are returning the First tab
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
i tried to use the getItemPosition but it didn´t work, my app crash when i select an tab.
Any ideias? please
android developers please help, I Have viewpager with fragments, when i slide in the pages and reached the last page and then when i return to the first page again the fragment of the first page loads its default display.Please help..here is my code in MainActivity
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private ActionBar actionBar;
private ViewPager pager;
private Menu menu;
private float lastTranslate = 0.0f;
private FrameLayout mainframe, galleryframe;
private Frag_Gallery fragGallery;
private Frag_Create fragCreate;
private Frag_Account fragAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.viewPager);
mainframe = (FrameLayout) findViewById(R.id.fragmentholder);
galleryframe = (FrameLayout) findViewById(R.id.galleryholder);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#0b115e"));
Main_Menu Menu_data[] = new Main_Menu[]
{
new Main_Menu(R.mipmap.gallery_icon, "Gallery"),
new Main_Menu(R.mipmap.create_icon, "Create Your Own"),
new Main_Menu(R.mipmap.account_icon, "My Account"),
new Main_Menu(R.mipmap.contact_icon, "Contact Us")
};
MainMenuAdapter adapter = new MainMenuAdapter(this,
R.layout.listviewmain_item_row, Menu_data);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
navList = (ListView) findViewById(R.id.navList);
View header = (View) getLayoutInflater().inflate(R.layout.listviewmain_header_row, null);
navList.addHeaderView(header);
navList.setAdapter(adapter);
navList.setDivider(null);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
loadSelection(position);
drawerLayout.closeDrawer(navList);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.opendrawer, R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle("");
fragmentManager = getSupportFragmentManager();
loadSelection(0);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int pos) {
switch (pos) {
case 0:
menu.getItem(0).setIcon(R.mipmap.gallery_icon);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
break;
case 1:
menu.getItem(0).setIcon(R.mipmap.gallery_icon_off);
menu.getItem(1).setIcon(R.mipmap.create_icon);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
break;
case 2:
menu.getItem(0).setIcon(R.mipmap.gallery_icon_off);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(0).setIcon(R.mipmap.gallery_icon);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
return true;
}
private void loadSelection(int i) {
switch (i) {
case 1:
actionBar.setTitle("Gallery");
pager.setCurrentItem(0, true);
break;
case 2:
actionBar.setTitle("Design");
pager.setCurrentItem(1, true);
break;
case 3:
actionBar.setTitle("Account");
pager.setCurrentItem(2, true);
break;
case 4:
actionBar.setTitle("Contact us");
break;
default:
actionBar.setTitle("");
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#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 == android.R.id.home) {
if (drawerLayout.isDrawerOpen(navList)) {
drawerLayout.closeDrawer(navList);
} else {
drawerLayout.openDrawer(navList);
}
}
return super.onOptionsItemSelected(item);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
fragment = new Fragment();
switch (pos) {
case 0:
fragment = new Frag_Gallery();
break;
case 1:
fragment = new Frag_Create();
break;
case 2:
fragment = new Frag_Account();
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
}
use
pager.setOffscreenPageLimit(X);
where X is the count of the pages you want to save so the ViewPager wont rebuild them.
I'm trying to use a NavigationDrawer with FragmentStatePagerAdapter for the navigation of my app. The idea is that when clicking on an item of the NavigationDrawer a new fragment opens with two tabs in it.
My problem is that I can't make it work correctly. When clicking on an item of the NavigationDrawer, instead of two tabs I get four, then six, ...
This problem can be solved with actionBar.removeAllTabs(), but my main problem is that when I come back on a previous fragment by re-clicking on the item of the NavigationDrawer (fragment 1 -> fragment 2 -> fragment 1), I got an empty fragment.
I tried to solve this problem by make some changes according to what's stated on other pages, but I didn't succeed in making it work.
Any help would be appreciated, thank you!
Here is the class managing my main fragment:
public class FragmentMultiTab extends SherlockFragment {
private MyVariables mk;
private ActionBar actionBar;
private ViewPager viewPager;
private View rootView;
private int i;
#Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
final int[] fragment = { R.layout.fragment1, R.layout.fragment2,
R.layout.fragment3 };
final int[] pager = { R.id.pager1, R.id.pager2, R.id.pager3 };
this.mk = new MyVariables(this.getArguments());
i = this.mk.getInt("INDEX");
this.rootView = inflater.inflate(fragment[i], container, false);
viewPager = (ViewPager) this.rootView.findViewById(pager[i]);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
viewPager.getAdapter().notifyDataSetChanged();
addActionBarTabs();
return rootView;
}
private final ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
actionBar.setSelectedNavigationItem(position);
}
};
private void addActionBarTabs() {
actionBar = getSherlockActivity().getSupportActionBar();
final String[][] tabTitle = {{"Tab 1","Tab 3","Tab 5" },{"Tab 2","Tab 4",
"Tab 6" } };
for (int k = 0; k < 2; k++) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle[k][i])
.setTabListener(tabListener);
actionBar.addTab(tab);
}
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private final ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
}
Here is the ViewPager used
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 2;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
}
return null;
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return PAGE_COUNT;
}
}
My fragments have the following structure:
<RelativeLayout 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" >
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
And finally here is my MainActivity:
public class MainActivity extends SherlockFragmentActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
FragmentMultiTab fragment1 = new FragmentMultiTab();
FragmentMultiTab fragment2 = new FragmentMultiTab();
FragmentMultiTab fragment3 = new FragmentMultiTab();
private final MyVariables mk = new MyVariables();
private int currentPosition;
#Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
this.mDrawerToggle.onConfigurationChanged(newConfig);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
MainActivity.this.selectItem(position);
}
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
currentPosition = -1;
// Locate DrawerLayout in activity_main.xml
this.mDrawerLayout = (DrawerLayout) this
.findViewById(R.id.drawer_layout);
// Locate ListView in activity_main.xml
this.mDrawerList = (ListView) this.findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
this.mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
this.mMenuAdapter = new MenuListAdapter(this);
// Set the MenuListAdapter to the ListView
this.mDrawerList.setAdapter(this.mMenuAdapter);
// Capture button clicks on side menu
this.mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
this.getSupportActionBar().setHomeButtonEnabled(true);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
this.mDrawerToggle = new ActionBarDrawerToggle(this,
this.mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,R.string.drawer_close) {
#Override
public void onDrawerClosed(final View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
#Override
public void onDrawerOpened(final View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
this.mDrawerLayout.setDrawerListener(this.mDrawerToggle);
if (savedInstanceState == null) {
this.selectItem(0);
}
this.mk.setVariables(this);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
this.getSupportMenuInflater().inflate(R.menu.action_bar_main, menu);
this.getActionBar().setDisplayHomeAsUpEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (this.mDrawerLayout.isDrawerOpen(this.mDrawerList)) {
this.mDrawerLayout.closeDrawer(this.mDrawerList);
} else {
this.mDrawerLayout.openDrawer(this.mDrawerList);
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
this.mDrawerToggle.syncState();
}
private void selectItem(final int position) {
final FragmentTransaction ft = this.getSupportFragmentManager()
.beginTransaction();
if (currentPosition != position)
// Locate Position
switch (position) {
case 0:
this.mk.addInt("INDEX", 0);
this.mk.addBoolean("START", false);
this.fragment1.setArguments(this.mk.getArgs());
ft.replace(R.id.content_frame, this.fragment1);
break;
case 1:
this.mk.addInt("INDEX", 1);
this.fragment2.setArguments(this.mk.getArgs());
ft.replace(R.id.content_frame, this.fragment2);
break;
case 2:
this.mk.addInt("INDEX", 2);
this.fragment3.setArguments(this.mk.getArgs());
ft.replace(R.id.content_frame, this.fragment3);
break;
}
currentPosition = position;
ft.commit();
this.mDrawerList.setItemChecked(position, true);
// Close drawer
this.mDrawerLayout.closeDrawer(this.mDrawerList);
}
}
I'd suggest using the ViewPagerIndicator instead of the standard ActionBar Tabs (they have some issues with regards to being converted into dropdown menus in some cases. The interface is quite simply (you just hook your viewpagerindicator to a viewpager), and you'll probably solve your issue as well.