Android Viewpager show wrong pages - android

I have a viewpager and in that viewpager i have 6 pages.All of the pages contains listviews.Sometimes viewpager shows wrong pages at wrong indexes.Here is my viewpager adapter:
public class TestFragmentAdapter extends FragmentPagerAdapter{
protected static final String[] CONTENT = new String[] { "a","b","c","d","e","f" };
private int mCount = CONTENT.length;
Fragment fragment1,fragment2,fragment3,fragment4,fragment5,fragment6;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
fragment1 = new CategoryListView();
fragment2 = CustomizedListviewRecent.newInstance(41);
fragment3 = CustomizedListviewMostRecents.newInstance(0);
fragment4 = CustomizedListviewPopulars.newInstance();
fragment5 = CustomizedListviewRecent.newInstance(42);
fragment6 = CustomizedListviewRecent.newInstance(43);
}
#Override
public Fragment getItem(int position) {
if(position == 0)
return fragment1;
else if(position == 1)
return fragment2;
else if(position == 2)
return fragment3;
else if(position == 3)
return fragment4;
else if(position == 4)
return fragment5;
else
return fragment6;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
Here is how i create my viewpager:
public class SampleTitlesDefault extends BaseSampleActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
mIndicator.setCurrentItem(1);
}
}
Thanks for your help

try this:
public class TestFragmentAdapter extends FragmentPagerAdapter{
protected static final String[] CONTENT = new String[] { "a","b","c","d","e","f" };
ArrayList<Fragment> fragments;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
fragments.add(new CategoryListView());
fragments.add(CustomizedListviewRecent.newInstance(41));
fragments.add(CustomizedListviewMostRecents.newInstance(0));
fragments.add(CustomizedListviewPopulars.newInstance());
fragments.add(CustomizedListviewRecent.newInstance(42));
fragments.add(CustomizedListviewRecent.newInstance(43));
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
}

this mIndicator.setCurrentItem(1);
must replace by this mPager.setCurrentItem(1);

Related

Fragments not being loaded using PagerAdapter [ANDROID]

In my app i am using pager adapter to load 2 fragments, the fragments are not getting loaded and view pager remains null. Where i am going wrong? Any help will be appreciated
Here is my code
I am setting this adapter to my view pager from activity
public class ViewPagerActivityAdapter extends PagerAdapter {
ArrayList<Fragment> tablist;
public ViewPagerActivityAdapter(ArrayList<Fragment> tablist) {
this.tablist = tablist;
}
#Override
public int getCount() {
return tablist.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
return null;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
}
}
Activity Part
private ViewPagerActivityAdapter viewPagerAdapter;
private ArrayList<Fragment> fragments_faq;
fragments_faq = new ArrayList<>();
FragmentOne frag1 = new FragmentOne();
tablayout.addTab(tablayout.newTab().setText("fragone"));
fragments_faq.add(frag1);
FragmentTwo frag2 = new FragmentTwo();
tablayout.addTab(tablayout.newTab().setText("fragtwo"));
fragments_faq.add(frag2);
private void setPagerAdapter() {
viewPagerAdapter = new ViewPagerActivityAdapter(fragments_faq);
viewpager.setAdapter(viewPagerAdapter);
viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
viewpager.setOffscreenPageLimit(2);
tablayout.addOnTabSelectedListener(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 Fragment getItem(int position) {
return this.fragments.get(position);
}
for details check this gist
https://gist.github.com/vinay6kr/33359c3f3b0e9f28e33bd383b01e9d9f
if you want to show fragments in viewpager you should use FragmentStatePagerAdapter
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
public MyViewPagerAdapter(FragmentManager fm, CharSequence mTitles[]) {
super(fm);
this.Titles = mTitles;
}
#Override
public Fragment getItem(int position) {
if (position == 0)
return new Fragment1().getInstance();
else if (position == 1)
return new Fragment2().getInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return Titles.length;
}
}
and to Set them
void setUpTabs() {
String Titles[] = {"Frag1","Frag2"};
MyViewPagerAdapter adapter = new MyViewPagerAdapter(this.getSupportFragmentManager(), Titles);
viewPager.setAdapter(adapter);
}
You can try like adapter look like
class ViewPagerActivityAdapter extends FragmentPagerAdapter {
// fragments to instantiate in the viewpager
private List<Fragment> fragments;
// constructor
public ViewPagerActivityAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
// return access to fragment from position, required override
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
// number of fragments in list, required override
#Override
public int getCount() {
return this.fragments.size();
}
}
Add Fragment
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,
FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this,
FragmentTwo.class.getName()));
Add to view Pager
ViewPagerActivityAdapter mPagerAdapter;
this.mPagerAdapter = new ViewPagerActivityAdapter(
super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) super.findViewById(R.id.pager);
mPager.setAdapter(this.mPagerAdapter);
You should use FragmentPagerAdapter or FragmentStatePagerAdapter for this.Here is sample code.
public class ViewPagerActivityAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> tablist;
public ViewPagerActivityAdapter(ArrayList<Fragment> tablist) {
this.tablist = tablist;
}
#Override
public int getCount() {
return tablist.size();
}
#Override
public Fragment getItem(int position) {
return tablist.get(position);
}
}

how to get the text of text-view inside view-pager current page in Toast

I want to get the TextView text of current page of ViewPager in toast in onPageSelected() . Remember my data is in array-list , if I remove any position from array-list that text should not be shown in toast on swipe view-pager.
Below is my code:
public class MainActivity extends FragmentActivity {
public static TextView tx;
CustomViewPager pager1;
List<Fragment> fragments1;
public PagerAdapter adapter1;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
pager1 = (CustomViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new PagerAdapter(getSupportFragmentManager(), fragments1);
pager1.setAdapter(adapter1);
removeView1(1);
adapter1.notifyDataSetChanged();
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
String S= (String) tx.getTag();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +S, Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
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 position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public int getItemPosition (Object object)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
return position;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < image.size(); i++) {
fList.add(MyImageSlider.newInstance(image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
String newid;
public static MyImageSlider newInstance(String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
tx = (TextView)view.findViewById(R.id.text);
tx.setText(newid);
tx.setTag(newid);
return view;
}
}
}
Please try this code
public class MainActivity extends FragmentActivity {
public static TextView tx;
CustomViewPager pager1;
List<Fragment> fragments1;
public PagerAdapter adapter1;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
pager1 = (CustomViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new PagerAdapter(getSupportFragmentManager(), fragments1);
pager1.setAdapter(adapter1);
removeView1(1);
adapter1.notifyDataSetChanged();
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
MyImageSlider fragmntDta = (MyImageSlider ) findFragmentByPosition(mCurrentPos);
String value = fragmntDta.getTextOnTextView();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +value, Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
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 position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public int getItemPosition (Object object)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
return position;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < image.size(); i++) {
fList.add(MyImageSlider.newInstance(image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
String newid;
TextView textView;
public static MyImageSlider newInstance(String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextOnTextView(){
retrun textView.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
textView = (TextView)view.findViewById(R.id.text);
textView.setText(newid);
textView.setTag(newid);
return view;
}
}
public Fragment findFragmentByPosition(int position) {
MyImageSlider fragmentPagerAdapter = mAdapter;
return getSupportFragmentManager().findFragmentByTag("android:switcher:" + mHorizontalViewPager.getId() + ":" + fragmentPagerAdapter.getItemId(position));
}
}
you should follow AndiGeeky's solutions.
In addition to that solution, you can even get a view which is visible on that position.
View view = pager1.getChildAt(position);
and later on get that textview by using view.findViewById(R.id.textviewid)
your code should look something like this.
#Override
public void onPageSelected(int position) {
View view = pager1.getChildAt(position);
TextView tv = (TextView)view.findViewById(R.id.<textviewId>);
Toast toast = Toast.makeText(getApplicationContext(),"Text is " + tv.getText().toString(), Toast.LENGTH_SHORT);
toast.show();
}
Note : textviewId will be the id of your TextView which is in Fragment

Can't remove fragment from its arraylist

I have a program that has fragment as arraylist, I am using it with TabLayout , As I remove a tab I want to remove the fragment also. But with my implementation it is not sequential. Tab 1 will remove Fragment2 etc. Please check where I am going wrong ?
Under onCreate of MainActivity this is how I add fragments
private TabPagerAdapter pagerAdapter;
public List<Fragment> fragmentList = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
fragmentList.add(NewsFragment.newInstance(Tab1));
fragmentList.add(NewsFragment.newInstance(Tab2));
fragmentList.add(NewsFragment.newInstance(Tab3));
mViewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), fragmentList);
mViewPager.setAdapter(pagerAdapter);
This is my FragmentStatePagerAdapter, removeFragment is where I am trying to remove the fragment
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList;
private List<String> tabTitles = new ArrayList<>();
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
mFragmentList = fragmentList;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void removeFragment(int tabPosition) {
if (!mFragmentList.isEmpty()) {
mFragmentList.remove(tabPosition);
}
}
}
OnActivity result under mainactivity is where I am trying to remove both the tab & fragment
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK || data == null)
return;
settingList = (ArrayList<SettingCheckBox>) data.getSerializableExtra(SETTING_CHECK_BOX);
for (int i = 0; i < settingList.size(); i++) {
if (settingList.get(i).getChecked()) {
Log.d("**Checked Item**", String.valueOf(settingList.get(i).getDescription()));
String removeTab = String.valueOf(settingList.get(i).getDescription());
Boolean checkedValue = settingList.get(i).getChecked();
if (removeTab.equals("tab1")) {
//remove tab
tabLayout.removeTab(tab1);
//remove fragment
pagerAdapter.removeFragment(0);
// fragmentList.remove(i);
pagerAdapter.notifyDataSetChanged();
} else if (removeTab.equals("tab2")) {
tabLayout.removeTab(tab2);
pagerAdapter.removeFragment(1);
// fragmentList.remove(i);
pagerAdapter.notifyDataSetChanged();
} else if (removeTab.equals("tab3")) {
tabLayout.removeTab(tab3);
pagerAdapter.removeFragment(2);
// fragmentList.remove(i);
pagerAdapter.notifyDataSetChanged();
}
change you pagerAdapter.removeFragment(mViewPager.getCurrentItem()); to pagerAdapter.removeFragment(correctFragmentPosition);
correctFragmentPosition = calculate based on value of removeTab
Just to answer my own question. I added the fragment this way
public List<Fragment> fragmentList = new ArrayList<>();
private NewsFragment frag1
frag1 = NewsFragment.newInstance("https://www.yahoo.com");
fragmentList.add(frag1);
In case I need to find the position of the fragment
for (int i = 0; i < fragmentList.size(); i++) {
if (fragmentList.get(i).equals(frag1)) {
//found the position so removing it
pagerAdapter.removeFragment(i); }
}

Accessing Fragment from viewpager returns null everytime?

My host activity has a viewpager with two fragments A and B.My activity code looks like this:
public class MainActivity extends AppCompatActivity implements
OnDataLoadedListener {
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabLayout.setupWithViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "A",
"B" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return A.getInstance();
case 1:
return B.getInstance();
}
return null;
}
}
public Fragment findFragmentByPosition(int position) {
return getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + pager.getId() + ":"
+ adapter.getItemId(position));
}
Now when activity start viewpager get populated with fragment properly and I try to access fragmentby using following code:
if (AFragment == null)
AFragment = (A) findFragmentByPosition(0);
if (BFragment == null)
BFragment = (B) findFragmentByPosition(1);
But AFragment and BFragment always contains null.I have read other simmilar question but it didn't help either.I need access to fragments as I want to call some methods defined in fragment from host activity.
Code to get an instance of fragment:
public static AFragment getInstance() {
AFragment fragment = new AFragment();
return fragment;
}
I'm think that the problem is that you need to move the method to the Adapter, because you need the original instance of the FragmentManager :
public class MyPagerAdapter extends FragmentPagerAdapter {
FragmentManager fm;
private final String[] TITLES = { "A",
"B" };
public MyPagerAdapter (FragmentManager fm) {
super(fm);
this.fm = fm;
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return A.getInstance();
case 1:
return B.getInstance();
}
return null;
}
public Fragment findFragmentByPosition(int position, int pagerId) {
return fm.findFragmentByTag(
"android:switcher:" + pagerId + ":"
+ getItemId(position));
}
}
So now you can call:
adapter.findFragmentByPosition(position, pager.getId());

Viewpager and Sherlock Fragments. How to do somethng inside fragment from FragmentActivity?

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.

Categories

Resources