After the device goes on standby, if I call getSupportFragmentManager() I get a FragmentManager that contains fragments not initialised with all their variables set to null.
Here there is some code:
this.mAdapter = new MyAdapter(getSupportFragmentManager());
this.mPager = (ViewPager) findViewById(R.id.pager);
this.mPager.setAdapter(mAdapter);
TabPageIndicator titleIndicator = (TabPageIndicator) findViewById(R.id.titles);
titleIndicator.setViewPager(mPager);
titleIndicator.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
mAdapter.getItem(position).onFocus();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
This is MyAdapter class:
public static class MyAdapter extends FragmentStatePagerAdapter
{
ArrayList<ExtendedFragment> tabs = new ArrayList<ExtendedFragment>();
String[] titles = new String[] { "FRAG1", "FRAG2", "FRAG3", "FRAG4", "FRAG5", "FRAG6"};
public MyAdapter(FragmentManager fm)
{
super(fm);
tabs.add(new frag1());
tabs.add(new frag2());
tabs.add(new frag3());
tabs.add(new frag4());
tabs.add(new frag5());
tabs.add(new frag6());
}
#Override
public int getCount()
{
return tabs.size();
}
#Override
public ExtendedFragment getItem(int position)
{
return tabs.get(position);
}
#Override
public CharSequence getPageTitle(int position)
{
return titles[position];
}
}
The ExtendedFragment implements the method onFocus(), each fragment override that because i need to do some actions when a tab gets the focus. When I resume the device from standby and onFocus() is fired, if I try to get the View using getView() I get null.
Why my view is null?
You could try overriding onSaveInstanceState method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mContentFragment = getSupportFragmentManager().getFragment(
savedInstanceState, "mContent");
}
if (mContentFragment == null) {
mContentFragment = new YourFragment();
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent",
mContentFragment);
}
Related
I have a problem in my Application, I load a fragment in my activity and in the fragment i used the ViewPager(for TabLayout) so i want to handle the BackPressed of ViewPager.
Because there is no OnKeyDown override method is available in fragment so i want the refrence of my Fragment ViewPager in my Parent Activty so i can handle this situation in onBackPressed() method Activity.
Activity Code :
fragment= new TabFragment();
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.containerView, fragment);
ft.commitAllowingStateLoss();
// ft.commit();
}
#Override
public void onBackPressed() {
if (isMainShown) {
// want the refrence of view pager so i can handle ViewPager on backPress
}
else {
//display tab fragment
}
//super.onBackPressed();
}
TabFragment :
public class TabFragment extends Fragment {
public TabFragment() {
// Required empty public constructor
}
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ; View x;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
x=inflater.inflate(R.layout.content_main_menu,null);
tabLayout=(TabLayout) x.findViewById(R.id.tabs);
viewPager =(ViewPager) x.findViewById(R.id.viewpager);
setupViewPager(viewPager);
//viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOffscreenPageLimit(1);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private void setupViewPager(ViewPager viewPager) {
MyAdapter adapter = new MyAdapter(getChildFragmentManager());
adapter.addFragment(new TabOne(), "TAb1");
adapter.addFragment(new TabTwo(), "Tab2");
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
final InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(x.getWindowToken(), 0);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private class MyAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
}
}......
add this code in your onBackPressed()
fragobjTab = (TabFragment) getSupportFragmentManager().findFragmentById(R.id.containerView);
try {
fragobjTab.onBackPressed();
}catch (Exception e){
e.printStackTrace();
}
And create a onBackPressed method in your tabFragment and setCurrentItem to the ViewPager:
public void onBackPressed()
{
// set page to your viewPager
// 0 is your first viewpager fragment
viewPager.setCurrentItem(0,true);
}
I have an activity and pager adapter in it which displays 3 fragments. The fragments are shuffled. I need to know the number of each page when I am swiping through them and that number needs to be displayed in a textView. For example, when I am in the first page number 1 is displayed, second page - number 2 and so on.
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int arg0) {
return this.fragments.get(arg0);
}
#Override
public int getCount() {
return this.fragments.size();
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
}
mainActivity.java
public class testActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_adapter);
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you want to be displaying the number in your fragment, use this
In your Activity
#Override
public Fragment getItem(int position) {
// Here you can add an argument that will be passed to the fragment
// In your case you need to pass the page number
Fragment fragment = this.fragments.get(arg0);
Bundle b = new Bundle();
b.putInt("page_number", position);
fragment.setArguments(b);
return fragment;
}
In you fragment do this
int number;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read the data that Activity passed to us
if (savedInstanceState == null) {
Bundle args = getArguments();
if (args != null) {
number = args.getInt("page_number") + 1;
}
}
else {
number = savedInstanceState.getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Here you need to find your TextView and show the number
View v = inflater.inflate(R.layout.some_layout, container, false);
((TextView) v.findViewById(R.id.someTextView)).setText(String.format("%d", number));
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("page_number", number);
}
If you want to be displaying the number in your Activity, use this
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
// !!! Change ME!!!!!
textView = (TextView) findViewById(R.id.someTextView);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
textView.setText("Position: " + i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
pager.setAdapter(mPagerAdapter);
}
Use PageChangeListener as:
yourPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
yourTextView.setText("Page: " + position);
}
... ...
});
I have a ViewPager that sets up two fragments as swipeable tabs. I am trying to find these fragments in the hosting activity.
I set them up as class global variables:
private SharedBillFragment sharedBill;
private SeparateBillFragment separateBill;
and try to find them in the activity's onStart():
#Override
protected void onStart() {
super.onStart();
findFragments();
}
where findFragments() is (I know this is kind of a hack, but it should work for the moment...):
private void findFragments() {
sharedBill = (SharedBillFragment)
getFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 0);
separateBill = (SeparateBillFragment)
getFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 1);
}
But this is not working, the fragments are not found. When i call findFragments() in a method that is called later (following a user interaction), the fragments are found and I can use them. Example:
private void setCountryTip(String selectedCountry) {
findFragments();
sharedBill.setPercentage(getCountryTip(selectedCountry));
separateBill.setPercentage(getCountryTip(selectedCountry));
}
But even when called then, the fragments are only available in the method where findFragments() is called, even though I set them as class global variables.
Best case, I would like to find the fragments when the app is started and store them in class global variables. Any help how to achieve that?
EDIT:
Some more information on how my fragments are setup. In my MainActivity I have:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] mTabTitles = getResources().getStringArray(R.array.tabs);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
mViewPager.setAdapter(mTabsAdapter);
for (String tab_name : mTabTitles) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
}
and my TabsAdapter:
public class TabsAdapter extends FragmentPagerAdapter {
final int NUMBER_OF_TABS = 2;
public TabsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SharedBillFragment();
case 1:
return new SeparateBillFragment();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_TABS;
}
}
EDIT: Regarding the NPE, my spinner is setup as follows in the fragment:
private Spinner spCountry;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
spCountry = (Spinner) getActivity().findViewById(R.id.spCountry);
spCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
mCallback.onCountrySelected(spCountry.getItemAtPosition(pos).toString());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void setCountry(String country) {
ArrayAdapter spCountryAdapter = (ArrayAdapter) spCountry.getAdapter();
spCountry.setSelection(spCountryAdapter.getPosition(country));
}
The spinner gets its entries via the xml property "android:entries".
Not a very nice and re-usable solution, but since you are using static fragments it could work: make the adapters type Fragment, and initialize the fragments in the activity. Than add the two fragment to the adapter, and in the adapters getItem function only return the corresponding fragment.
Adapter:
public class TabsAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
public TabsAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int index) {
return fragments.get(index);
}
#Override
public int getCount() {
return fragments.size();
}
}
Activity:
sharedBillFragment = new SharedBillFragment();
separateBillFragment = new SeparateBillFragment();
List<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(sharedBillFragment);
fragments.add(separateBillFragment);
mTabsAdapter = new TabsAdapter(getFragmentManager(), fragments);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
mViewPager.setAdapter(mTabsAdapter);
Find the spinner in the onCreateView like this:
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, containter, false);
spCountry = (Spinner) getActivity().findViewById(R.id.spCountry);
...
return v;
}
I am using options menu in action bar tabs,view pager and nested fragments, when i switch from fragmentA to fragmentB using tabs menu items are working fine, but when i try to swith using view pager option items are getting invisble in fragments.
public class RTHomeTabFragment extends Fragment implements TabListener,OnBackButtonPressInterfaceForFragment{
public ActionBarActivity parentActivity;
private ActionBar actionBar;
ViewPager mViewPager;
public static int currentPage;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RTMessagingUtils.log(getClass().getName(), "onCreateView");
View view = inflater.inflate(R.layout.viewpager_tabs, container,false);
parentActivity = (ActionBarActivity) getActivity();
actionBar = parentActivity.getSupportActionBar();
mViewPager = (ViewPager) view.findViewById(R.id.pager);
/* actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setCustomView(null);
actionBar.removeAllTabs();
List<Fragment> fragments = getFragments();
pagerAdapter adapter = new pagerAdapter(getChildFragmentManager(), getFragments());
mViewPager.setAdapter(adapter);
currentPage=mViewPager.getCurrentItem();
Log.d("TestFragments", "currentPage======"+currentPage);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
currentPage=mViewPager.getCurrentItem();
Log.d("TestFragments", "currentPage======"+currentPage);
}
});
for (int i = 0; i < adapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(adapter.getPageTitle(i)).setTabListener(this));
}
return view;
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// add fragments here
fList.add(new Test1());
fList.add(new Test2());
fList.add(new Test3());
return fList;
}
class pagerAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments;
public pagerAdapter(FragmentManager fm, List<Fragment> fragments){
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.db_jio_chat_chats).toUpperCase(l);
case 1:
return getString(R.string.db_jio_chat_groups).toUpperCase(l);
case 2:
return getString(R.string.db_jio_chat_contacts).toUpperCase(l);
/*case 3:
return getString(R.string.db_jio_chat_my_profile).toUpperCase(l);
case 4:
return getString(R.string.db_jio_chat_location).toUpperCase(l);
case 5:
return getString(R.string.db_jio_chat_about).toUpperCase(l);*/
}
return null;
}
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onResume() {
super.onResume();
RTMessagingUtils.log(getClass().getName(), "onResume");
}
#Override
public void onPause() {
super.onPause();
RTMessagingUtils.log(getClass().getName(), "onPause");
}
}
In your getItem method do this for testing :
#Override
public Fragment getItem(int position) {
if(position == 0)
return new Test1();
else
return new Test2();
}
and see if this works, I will find an explanation later if it works...
I have a parent SherlockFragmentActivity class that contains ViewPager with 4 Fragments inside.
One of them extends from SherlockListFragment and I want to scroll it to top by click on it's tab.
MainActivity class:
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
TabAdapter tabAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(Constants.THEME);
viewPager = new ViewPager(this);
viewPager.setId(R.id.pager);
viewPager.setBackgroundResource(R.color.background_color);
tabAdapter = new TabAdapter(this,viewPager);
super.onCreate(savedInstanceState);
setContentView(viewPager);
// Action bar setup
setupTabs(savedInstanceState);
}
private void setupTabs(Bundle savedInstanceState) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i = 1; i <= 4; i++) {
ActionBar.Tab tab = getSupportActionBar().newTab();
switch (i) {
case 1:
tab.setText(R.string.feed).setTabListener(tabAdapter);
tabAdapter.addTab(EventListFragment.class);
break;
case 2:
tab.setText(R.string.downloads).setTabListener(tabAdapter);
tabAdapter.addTab(LocalEventListFragment.class);
break;
case 3:
tab.setText(R.string.tags).setTabListener(tabAdapter);
tabAdapter.addTab(TagsFragment.class);
break;
case 4:
tab.setText(R.string.settings).setTabListener(tabAdapter);
tabAdapter.addTab(SettingsFragment.class);
break;
}
getSupportActionBar().addTab(tab);
}
}
TabAdapter class:
public static class TabAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
private final ActionBar mActionBar;
private final ViewPager mViewPager;
public TabAdapter(SherlockFragmentActivity activity, ViewPager pager){
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(Class<?> clss){
classes.add(clss);
mFragments.add(Fragment.instantiate(mContext, clss.getName(),
null));
}
#Override
public Fragment getItem(int i) {
return mFragments.get(i);
}
public int getId(int index){
return mFragments.get(index).getId();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// fixed double call onTabReselected
if (mActionBar.getSelectedNavigationIndex() != position)
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int i) {
}
#Override
public int getCount() {
return 4;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
final int position = tab.getPosition();
final Fragment fragment = mFragments.get(position);
if (fragment != null) {
switch (position) {
case 0:
// call tab's ListFragment scroll to top item
((EventListFragment) fragment).scrollToTop();
break;
case 1:
// do something
break;
}
}
}
onTabReselected called, then user press current tab, so I try to do EventListFragment scrolling:
EventListFragment class:
public class EventListFragment extends SherlockListFragment {
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mAdapter = new EventListAdapter(getSherlockActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View eventListLayout = inflater.inflate(R.layout.eventlist_fragment,null);
ListView lv = (ListView) eventListLayout.findViewById(android.R.id.list);
ViewGroup parent = (ViewGroup) lv.getParent();
//Remove ListView and add PullToRefreshListView in its place
int lvIndex = parent.indexOfChild(lv);
parent.removeViewAt(lvIndex);
mPullToRefreshListView = onCreatePullToRefreshListView(inflater, savedInstanceState);
parent.addView(mPullToRefreshListView, lvIndex, lv.getLayoutParams());
return eventListLayout;
}
public void scrollToTop() {
if (getSherlockActivity() != null) { // null after screen rotation
final ListView listView = getListView();
listView.post(new Runnable(){
public void run() {
listView.smoothScrollToPosition(0);
}});
}
}
It works on application start, but after screen rotation scrollToTop - getSherlockActivity() returns null.
If remove this condition check, have an exception:
java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
at com.project.fragment.EventListFragment.scrollToTop(EventListFragment.java:337)
at com.project.MainActivity$TabAdapter.onTabReselected(MainActivity.java:411)
at com.actionbarsherlock.internal.app.ActionBarWrapper$TabWrapper.onTabReselected(ActionBarWrapper.java:327)
I haven't totally understatinding how to ViewPager and its FragmentPagerAdapter works. So can't find a problem, that occurs.
Use this FragmentPageAdapter:
public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
};
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {Fragment f = null;
switch(position){
case 0:
{
f = new ArrayListFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 1:
{
f = new HomeFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 2:
{
f = new EndlessCustomView();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
return f;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
This Activity:
public class BaseSampleActivity extends SlidingFragmentActivity {
private static final Random RANDOM = new Random();
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
protected ListFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.themed_titles);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
Applied solution according to this post:
MainActivity class:
//...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
FragmentManager manager = getSupportFragmentManager();
for (int i = 0; i < tabAdapter.getClasses().size(); i++) {
String className = tabAdapter.getClasses().get(i).getName();
if (manager.findFragmentByTag(className) != null) {
manager.putFragment(outState, className, manager.findFragmentByTag(className));
}
}
}
//...
TabAdapter class:
//...
public void addTab(Class<?> clss, FragmentManager manager, Bundle savedInstanceState) {
classes.add(clss);
String className = clss.getName();
tags.add(className);
Fragment fragment;
if (savedInstanceState != null) {
fragment = manager.getFragment(savedInstanceState, className);
if (fragment == null) {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
} else {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
mFragments.add(fragment);
}
//...
where createFragment is a simple method, that creates needed fragment by passed class name.