I'm very new to Android development and I have been trying make an application that allows users to flip either to the left or right to change fragments. I'm using a FragmentStatePagerAdapter for this.
I first, in a for loop, created each fragment separately in the main activity's OnCreate() method and added them to the FragmentManager fManager.
for(Day day: days){
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
this.fManager.beginTransaction().add(R.id.pager, fragment).commit();
}
fManager.executePendingTransactions();
I then set up UI elements and set the ViewPager's adapter like so
this.setUpUI();
mPager.setAdapter(mPagerAdapter);
The problem is is that I keep encountering this exception java.lang.IllegalStateException: Fragment Already Added...
I am very confused as to what is going on because the only place I add fragments to the FragmentManager is in the for-loop above. Do FragmentStatePagerAdapter's do something in the background that might cause this issue or am I not implementing my ScreenSlidePagerAdapter correctly?
Here is my code for the ScreenSlidePagerAdapter class:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public FragmentManager fm;
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
this.fm = fm;
}
#Override
public Fragment getItem(int position) {
Fragment f = fm.getFragments().get(position);
return f;
}
#Override
public int getCount() {
return fm.getFragments().size();
}
}
Input would be greatly appreciated.
You show create the fragments inside getItem(pos) method of Adapter. The adapter internally use the FragmentManager that you provide in constructor.
Some what like this:
#Override
public Fragment getItem(int position) {
Fragment f = new ScreenSlidePageFragment();
return f;
}
I think the FragmentStatePagerAdapter already adds the fragments to your Activity (in the getItem() method). Try to remove that for loop.
You are getting the Fragment that is already in the FragmentManager and when you return it, the PagerAdapter tries to add it, but it is already there.
You don't have to add the fragments to the FragmentManager yourself. That's the FragmentStatePagerAdapter's job, that's why it receives a FragmentManager reference. You only have to create and return the fragments in getItem() and the PagerAdapter will add the fragments to the FragmentManager.
I usually do what you are trying like this:
public class FragmentSliderAdapter extends FragmentStatePagerAdapter {
private List<Fragment> list = new ArrayList<Fragment>();
public FragmentSliderAdapter(FragmentManager fm) {
super(fm);
list.add(new LoginFragment());
list.add(new SignupFragment());
}
#Override
public Fragment getItem(int arg0) {
return list.get(arg0);
}
#Override
public int getCount() {
return list.size();
}
}
Using list is cleaner and a good approach, since you can control what fragments are added to your adapter.
On the activity that uses the adapter, I just do this:
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new FragmentSliderAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
And the activity xml I do:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
See if it helps !
Related
I'm having some problems when dealing with Fragment using ViewPager.
What I'm having:
An activity (say, MainActivity) that contains a ViewPager to display some Fragment(s). Some of them contains a callback interface, which will be called to do somethings in the MainActivity.
The MainActivity has a FragmentPagerAdapter class, which is used as the adapter of the ViewPager. And a List<Fragment> in FragmentPagerAdapter to store some Fragment that will be displayed on the ViewPager.
What I'm expecting:
First launch, the Fragment called the callback interface's methods when I hit a button in it and MainActivity did somethings inside that. It worked great.
After a screen rotation, I expected it to work the same as the first launch BUT
NullPointerException: attempt to invoke a method on a null reference object (particularly, the Fragment's interface) hit me in my face.
What I know:
- The getItem(int position) won't be called again once the Fragment is created. Instead the instantiateItem(ViewGroup container, int position) will be called.
- FragmentManager will store some Fragment in mActive.mValues
- ViewPager and fragments — what's the right way to store fragment's state? (I did reference to this and some other same topics on StackOverflow too.)
What I have tried and saw:
- Override instantiateItem(ViewGroup container, int position)
- Debugged for 1 day. I saw that when I pass getSupportFragmentManager() in MainActivity's onCreate() method to FragmentPagerAdapter's super constructor, in the first launch, it has an "address in memory", assume it was '1a1a1a1'. The mActive.mValues of FragmentManager saved some Fragment' "address in memory" which are identical to the List<Fragment> containing them (assume it was 'qwertyu'). Which meaned it was right.
But when I rotated the screen, passing the getSupportFragmentManager() again, the "address in memory" was completely different, assume '9f9f9f9'. And FragmentManager's mActive.mValues contained a different set of Fragment' "address in memory" too (assume 'abcdeff'), although the number of Fragment in it was equal to the number of Fragment that was saved on the first launch (before rotation).
I have added a Fragment to the List<Fragment> with a new "address in memory" (assume 'abababa'), has the callback interface. But when I hit the button in it, it was the Fragment that was in the FragmentManager's mActive.mValues after the rotation (with "address in memory" is 'abcdeff' as I assumed above), and that one didn't have the callback interface (due to not being set in MainActivity first). And caused the NullPointerException as mentioned above.
My questions now is:
- First of all, how to get rid of this problem!? It would be better to keep using FragmentPagerAdapter instead of another class. But I will consider using other class too.
- Second, can you explain why FragmentManager saved the Fragment instance before rotation. But after rotation, it creates a completely different Fragment instance but still uses it instead of the Fragment that was saved in the List<Fragment>?
Here is the code (I think I didn't use the instantiateItem(ViewGroup container, int position) method in the right way so it still caused the problem).
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Attach the SectionsPagerAdapter to the ViewPager
SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
}
//
//
//Adapter class
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private static final int PAGE_HOME = 0;
private int tabCount = 1;
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> fragmentTitleList = new ArrayList<>();
//private FragmentManager fragmentManager;
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
//fragmentManager = fm;
//Default HomeFragment
HomeFragment homeFragment = new HomeFragment();
//Callback interface
homeFragment.setOnCategoryFragmentChangedListener(new HomeFragment.OnCategoryFragmentChangedListener() {
//This method will be called when a button in HomeFragment is clicked
#Override
public void onAddNewCategory(String categoryName) {
addNewCategory(categoryName);
}
});
fragmentList.add(homeFragment);
fragmentTitleList.add("Home");
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return tabCount;
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
fragmentList.set(position, (Fragment) super.instantiateItem(container, position));
return fragmentList.get(position);
}
private void addNewCategory(String categoryName) {
CategoryFragment fragment = new CategoryFragment();
tabCount += 1;
fragmentList.add(fragment);
fragmentTitleList.add(categoryName);
notifyDataSetChanged();
}
}
}
Please help. I'm being insane for 2 days now...!
I believe android restarts the activity during orientation change thus making multiple instances of FragmentPagerAdapter and multiple set of instances of List.
I don't completely understand your question but I suspect instantiateItem doesn't do anything anyway. Doesn't the Fragment getItem(int pos) work without overriding instantiateItem()?
Oh well, right after i felt in sleep, I found the solution. It's true that I didn't use the instantiateItem() method in the right way. After debugging again, I found that the instantiateItem() method get call whenever I swipe (or choose if using TabLayout as well) to another Fragment, and even get call before getItem(int pos), no matter what it's the first launch or after rotation. Which is why I think we should set things up for the Fragment in the instantiateItem() method.
So here is how I use the instantiateItem() method now:
#Override
public Object instantiateItem(ViewGroup container, int position) {
fragmentList.set(position, (Fragment) super.instantiateItem(container, position));
Fragment fragment = fragmentList.get(position);
if (position == PAGE_HOME) {
((HomeFragment) fragment).setOnCategoryFragmentChangedListener(new HomeFragment.OnCategoryFragmentChangedListener() {
#Override
public void onAddNewCategory(String categoryName) {
addNewCategory(categoryName);
}
});
}
return fragment;
}
If anyone have a better solution, please just tell me if you don't mind. I will consider about it.
I've got an app with left navigation drawer, switching between different fragments. Inside one of those fragment I want to implement SlidingTabLayout.
So, what I did is I copied the SlidingTabLayout.java and SlidingTabStrip.java from Google's iosched app. I used them inside my fragment:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<mynamespace.widget.SlidingTabLayout
android:id="#+id/home_fragment_tabs"
android:background="?attr/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/home_fragment_pager"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_width="match_parent" />
</LinearLayout>
And then in my Fragment class, inside onCreateView method, I instantiated my pager and SlidingTabLayout like this:
mPager = (ViewPager) view.findViewById(R.id.home_fragment_pager);
mPager.setAdapter(new HomePagerAdapter(getActivity().getSupportFragmentManager()));
mTabs = (SlidingTabLayout) view.findViewById(R.id.home_fragment_tabs);
mTabs.setViewPager(mPager);
And this is my FragmentPagerAdapter:
class HomePagerAdapter extends FragmentPagerAdapter
{
private String[] tabs = { "Today", "This week", "With star" };
private Fragment[] tabFragments = {
new TodayTabFragment(),
new WeekTabFragment(),
new StarTabFragment()
};
public HomePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
return tabFragments[i];
}
#Override
public int getCount()
{
return 3;
}
#Override
public CharSequence getPageTitle(int position)
{
return tabs[position];
}
}
Also I got separate Fragment class and layout for each tab, which is nothing special. And it works, but as soon as I switch to other fragment with my navigation drawer, when I get back, content of one of tabs just dissapears. Mostly it happens to second tab. Also, if I select the HomeFragment from navigation drawer, when is already displayed, I get a nullpointerexception inside SlidingTabLayout.java at this line: mViewPager.setCurrentItem(i);
Any way of fixing it? I have no idea what to do. I guess my code would work, but inside activity. Possible to make it work inside fragment?
I also faced the same issue. Please use FragmentStatePagerAdapter instead of FragmentPagerAdapter which will solve this issue.
Solution:
What I did is instead of implementing FragmentPagerAdapter, I implemented PagerAdapter then I overriden the instantiateItem(ViewGroup container, int position) method and destroyItem() method.
Link, that helped me: http://developer.android.com/samples/SlidingTabsBasic/src/com.example.android.slidingtabsbasic/SlidingTabsBasicFragment.html
Can you try to change constructor of HomePagerAdapter to:
public HomePagerAdapter(SupportFragmentManager fm)
{
super(fm);
}
When you begin transaction instead of suuportfragmanager change it to childfragmentmanager
I'm looking for some ideas on how to do a simple listview with images while inside a SherlockFragment class; Which is then loaded into a ViewPager fragment. I've tried several examples listed below, each one I cannot get to successfully work. I'm not asking for someone to do it for me, I'm looking for advice on how to build one from someones experience to direct me for resources.
Examples i have tried
android fragment example
android sdk fragments
I assume that the listview with images is no problem.
To show fragments in a viewpager you should work with the support-library and go like this:
you create a layout with a viewpager:
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
create a fragment that inflates your layout in 1., your on onCreateView Method should conatin the following lines:
View v = inflater.inflate(R.layout.view_pager_layout, parent, false);
MyFragmentAdapter mMyPagerAdapter =
new MyFragmentAdapter (getChildFragmentManager());
// ... set data to pager
mMyPagerAdapter.setCountOfFragments(mCountOfFragments);
mViewPager = (ViewPager) v.findViewById(R.id.view_pager);
mViewPager.setAdapter(mMyPagerAdapter);
3.create a class that extends from FragmentStatePagerAdapter. This should look like this:
public class MyFragmentAdapter extends FragmentStatePagerAdapter{
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int position) {
// create here you listfragment that should be shown in your viewPager
Fragment fragment = new ...;
// you also can set data to this listFragment
Bundle bundle = new Bundle();
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return mCountOfFragments;
}
}
These Links were helpfull for me:
http://developer.android.com/training/animation/screen-slide.html
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
And also the sample of effectivenavigation (https://android.googlesource.com/platform/development/+/d80ee02/samples/training/EffectiveNavigation) is really helpful.
Need some help with my problem of updating pages while using viewpager. I am using a simple viewpager with FragmentStatePagerAdapter. All I want to do is get access to the current fragment/view so as I can update some textviews in my fragment/view. I searched around in the forum and came to know few things
- One of the ways to handle this is by setting tag in instantiateItem() call back of the adapter and retreive the view by findViewbyTag. I could not understand how to implement this and I am also not sure if that will work for FragmentStatePagerAdapter.
- I explored other options as suggested in various forums, but cannot make them work.
My code is very much same as in a android http://developer.android.com/training/animation/screen-slide.html. Basic components are the same (Fragment activity xml with some display components including a textview, viewpager xml with just a view pager in it, a Fragment class and the main FragmentActivity class). in my FragmentActivity class I have added a pageChangelistener to my viewpager so as I can do my textview changes during onPageSelected().
Any help is is appreciated.
Adding the code for reference.
Public class myActivity extends FragmentActivity
//Variable declarations
protected void onCreate(Bundle savedInstanceState) {
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
View CurrView;
OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
doTextViewChnges();//access the text view and update it based on pageSelected
---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
}
mPager.setOnPageChangeListener(pageChangelistener);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
in your OnPageChangeListener:
OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
ScreenSlidePageFragment currentFragment = (ScreenSlidePageFragment) mPagerAdapter.getItem(pageSelected)
doTextViewChnges();//access the text view and update it based on pageSelected
---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
}
i assume you want to access your fragments from your activity and update the views.Fragments are parts of activities and their views can be accessed by them. Fragments are created dynamically in viewadapters and there is no straight forward and easy way to Tag them. You may simply access a fragment by its index number.first one is 0 second one is 1 and so on...
//access your fragment(in your case your first fragment)
//this part should be inside your doTextViewChnges()
Fragment fragment = (Fragment ) adapterViewPager
.getFragment(0);
if (fragment != null) {
//call a public method inside your fragment to update your text view
fragment .updateYourTextView();
}
Edit: inside your fragment create the following method and update your textview from there.
void updateYourTextView() {
yourTextView.setText("yourtext");
}
I have five activities/screens that I would like to be able to swipe between, each has a different function but are interrelated hence the UI concept of swiping between each.
I have found many discussions around ViewPager and PagerAdapters etc. but cannot seem to find one where swiping switches between different activity screens.
Is this even possible? Could someone point me towards an example project of this with source code? Or show me how to adapt an existing tutorial to do what I wish?
Thanks so much, have a good one!
You can't use ViewPager to swipe between Activities. You need to convert each of you five Activities into Fragments, then combine everything in one FragmentActivity with the Adapter you use with ViewPager.
Here's a link that goes into detail on converting your current Activities info Fragments.
This is the Fragment topic on the Android Developers website, it has a lot of useful info.
Here's another example (full source) that inflates TextViews on each page.
Here's an example that I typed up:
PagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment) {
mFragments.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
This should be called in onCreate of your FragmentActivity:
private void initPaging() {
FragmentOne fragmentOne = new FragmentOne();
FragmentTwo fragmentTwo= new FragmentTwo();
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(fragmentOne);
pagerAdapter.addFragment(fragmentTwo);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
}
This is an example of the layout you'd use for your FragmnetActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
To create Fragment create a new class that extends Fragment. The first two methods you'll want to override are onActivityCreated and onCreateView.
Here's how you could do that:
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(THE_LAYOUT_FROM_YOUR_ORIGINAL_ACTIVITY, container, false);
return view;
}
}
Fix For mPageradapter
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(fragmentOne);
pagerAdapter.addFragment(fragmentEvents);
viewPager = (ViewPager) super.findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);