Android studio - tabbed activity how to reset fragment to default view? - android

I have one fragment where are three (default) images and when user click on them, they will change to another. But when i swipe to another fragment and back to fragment with images there are not default ones as on the start. When I swipe two times so I will pass to another fragment (distance from original with images is 2 fragments) images are resetted to default. I was trying to implement setOffscreenPageLimit() from ViewPager and set it to 1, but minimum "length" when views in fragments are resetted is 2. How can I change that images to default manually after swipe action? Thank you.
Edit: I think that issue why onResume() is not working here: Fragment onResume not called
but i dont know what that means :/ I have three classes FragmentController.class, PagerAdapter.class and class of specific fragment for example FirstFragment.class. I don't know how connect these classes together.

Check that you create the fragments in the getItem() method of the adapter and do not hold any reference to that fragments (only WeakReferences if necessary), otherwise the fragments could not be destroyed.
EDIT:
The first fragment is unloaded only when you are in the third one because setOffscreenPageLimit is at least 1 so a viewpager allways loads the fragments that are at both sides of the selected one.
What you could do is to update your adapter with this code to provide a getFragment(position) method:
private HashMap<Integer, WeakReference<Fragment>> fragmentReferences = new HashMap<>();
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = FirstFragment.newInstance();
break;
// etc
}
fragmentReferences.put(position, new WeakReference<>(fragment));
return fragment;
}
public Fragment getFragment(int position) {
WeakReference<Fragment> ref = fragmentReferences.get(position);
return ref == null ? null : ref.get();
}
After then you can get the selected fragment and call the method you want from the first fragment when a page is selected:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int currentPage) {
if (currentPage == 0) {
Fragment firstFragment = adapter.getFragment(0);
if (firstFragment != null) {
// This method resets the images of the first fragment
((FirstFragment) firstFragment).reset();
}
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Do nothing
}
#Override
public void onPageScrollStateChanged(int state) {
// Do nothing
}
});

Related

Data transfer with tabs to ViewPager

I am trying to use ViewPager and TabLayout in different ways than the usual.
I have 5 tabs, and each tabs have ViewPager which has two fragment pages (A Fragment and B Fragment)each.
For each tab, ViewPager needs to display same fragment pages with different information. ( Such as Tab's title is displayed in A Fragment, and Tab 1's title is "Android", and Tab 2's title is "IOS" )
Since FragmentPagerAdapter sets the Fragments in getItem(int position) method like the below, I tried to send these information in that method (information about the tab).
I found the problem,when i launch the ViewPager and set the adapter to it, the adapter is only stetted once So, when Tab 1's ViewPager already set to A Fragment the title of "Android", it won't change to "IOS" when I turn it to second tab Tab2.
Is there any way sending different informations each tab to the ViewPager to receive the information differently?
I kind of wrote it too broad maybe? if you need more specific informations, or do not get the question please tell me I will explain you more.
Thanks for helping
My FragmentPagerAdapter
public class ManagerPagerAdapter extends FragmentPagerAdapter{
....
#Override
public Fragment getItem(int position){
...
/* I received informations about the tab, and setted to bundle.
So thought each tab gives different bundle data to AFragment.
But since the Adapter is setted only once, this method is not
called more than once*/
Bundle bundle = new Bundle();
switch(position){
case 0:
AFragment fragment_a = new AFragment();
fragment_a.setArguments(bundle);
return fragment_a;
case 1: //Not really matters
BFragment fragment_b = new BFragment();
return fragment_b;
}
}
}
My TabLayout code is not so different from other examples.
Thank you again!!!
If the Activity needs to be able to listen for changes to the page selected or other events surrounding the ViewPager, then we just need to hook into the ViewPager.OnPageChangeListener on the ViewPager to handle the events:
pager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// This method will be invoked when the current page is scrolled
}
public void onPageSelected(int position) {
// set your title here for specic fagment
//This method will be invoked when a new page becomes selected.
}
public void onPageScrollStateChanged(int state) {
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
}
});

How to communicate between fragment that holds the viewpager and viewpager's fragments (MVP)?

I'm building a mvp application and i'm looking for a clean and correct way to communicate between main fragment and those viewpager's fragments.
More specific,I have :
JobsFragment : fragment which contains the view pager
NewJobsFragment : one of view pager fragments
RecommendedJobsFragment : 2rd fragment from viewpager
SavedJobsFragment : 3rd fragment from viewpager
All viewpager's fragments contain a RecyclerView.Each part uses a MVP structure ( JobsFragment has it's own JobsPresenter,NewJobsFragments has NewJobsPresenter and so on)
User can filter the jobs in each fragment.Those filters can be selected from JobsFragment and when this is happening I need to 'notify' current fragment from viewpager and send those filters to it.
I read about child-parent relationship between presenters but I don't think it's a proper solution.
I also think about sharing a single presenter for all fragments but it's a lot of code and I guess it won't be readable anymore.
Thanks in advance !
Create one Abstract Fragment that extends Fragment. like this
public abstract BaseChildFragment extends Fragment{
public void onViewPagerPagechange();
}
Make All ChildFragment (JobsFragment , NewJobsFragment etc) extends BaseChildFragment ,
On your Pager Adapter add below code.
LruCache<Integer,BaseChildFragment> cache = new LruCache<>(4);
public BaseChildFragment getBaseChildFragment(int position){
return cache.get(position);
}
#Override
public Fragment getItem(int position) {
if (position == JOB) {
if (Utility.isEmpty(fragmentProfile)) {
jobsFragment = JobsFragment .getInstance()
cache.put(position,fragmentProfile );
}
return jobsFragment ;
} else if (position == NEW_JOB) {
......
return fragment;
}
return null;
}
On your Fragment that has View pager AddpageChangeListener like this
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// optional
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
// optional
#Override
public void onPageSelected(int position) {
BaseChildFragment fragment = adapter.getBaseChildFragment(position);
fragmeng.onViewPagerPagechange();
//you can invoke presenter logic by calling this method on each child presenter will call your filter (its upto you)
}
// optional
#Override
public void onPageScrollStateChanged(int state) { }
});
This will call your ChildFragment onViewPagerPagechange(); method. where you can load your child fragments. you can also get currently selected fragment. and simplest way is that you can get current fragment and check with getInstance();

Android Fragment Activity initialized variable is giving null value

I've created tab view using the code example on the android web.
http://developer.android.com/training/implementing-navigation/lateral.html
I've added this code to call a the setTitle method which would set the title.
mViewPager.addOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
FragmentInterface f = (FragmentInterface) mSectionsPagerAdapter
.getItem(position);
f.setTitle();
}
});
In my fragment class, I've define setTitle as
#Override
public void setTitle() {
System.out.println("Title " + cellMain);
if (cellMain != null) {
getActivity().getActionBar()
.setTitle(cellMain.cellData.getIPWithPort());
}
}
and I also have a button which does :
public void connect(View view) {
System.out.println("Connect " + cellMain);
if (cellMain == null) {
cellMain = CellMain.createAndroid(this,
getActivity().getFilesDir().toString());
getActivity().getActionBar()
.setTitle(cellMain.cellData.getIPWithPort());
}
First I click the button which calls connect,
It prints out "Connect null" which is expected as it has not been initialized.
Pressing the button again print out "Connect cell.CellMain#....".
Now I change the view by selecting another tab and changing back to the same tab.
setTitle() method prints out "Title null" which is not expected as cellMain is initialized. Pressing of the button still prints out "Connect cell.CellMain#...."
Why does my setTitle method give a null value for my variable?
Guess it's due to the fragments lifecycle inside the ViewPager.
The ViewPager has a limit of pages that are active, being those the current one and it's closer fragments (e.g: if the limit is 3, you will have active the current fragment shown, it's next and it's previous). The rest will got through the onPause() method.
The same happens when resuming a fragment. When you bring a fragment to the front, the fragments in that ranged that aren't active will go through the onResume method.
Depending on the number of fragments you have, you can think in different solutions.
If you have two or three fragments, change the offsetLimit of the viewPager to contain all of them.
viewPager.setOffscreenPageLimit(3);
If you have more fragments, think about saving it's state on the onPause() method, and restoring it on the onResume() of each fragment.
I've notice the mSectionsPagerAdapter.getItem(position) returns a new instance of the fragment which results in the variable always being null.
I've manually instantiated each fragment in the constructor and return them accordingly.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
String[] classes;
Fragment[] fragments;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
classes = new String[]{CellView.class.getName(),
ControlPanelView.class.getName()};
fragments = new Fragment[classes.length];
for (int i = 0; i < classes.length; i++) {
fragments[i] = Fragment.instantiate(context, classes[i]);
}
}
#Override
public Fragment getItem(int position) {
//Used to be this line
//return Fragment.instantiate(context, classes[i])
return fragments[position];
}

How to replace fragment in viewpager after instantiation?

I understand that the offscreen page limit for a viewpager must be at least 1. I am trying to dynamically change the fragments in my viewpagers as I am constantly grabbing information from a server.
For example, I have Fragments A, B, C instantiated when I am viewing Fragment B.
I want to change Fragment A's info, so I update it and call notifyDataSetChanged(). I have not created a new Fragment and inserted it in its place, but changed the imageview associated with the original fragment.
However, once I try to navigate to A, I run into an error saying "Fragment is not currently in the FragmentManager "
Can anyone explain to me how I'd be able to jump back and forth between immediate pages in a viewpager while allowing these pages to change their views?
I didn't do that, but my suggestion will be not to try to. Android does a lot of magic under the hood, and it is very possible you'll face a lot of issues trying to implement what you want. I had an experience with ListView when I was trying to save contentView for each list item, so that Android will render them only once, after the whole day I gave up the idea because every time I've changed the default behavior, something new came up (like exceptions that views are having two parents). I've managed to implement that, but the code was really awful.
Why don't you try, for example, save the image you've downloaded on the disc, and retrieve if when fragment actually appears on the screen ? Picasso library could help in this case
To do that, you should create a FragmentPagerAdapter that saves references to your pages as they are created. Something like this:
public class MyPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return MyListFragment.newInstance(TAB_NAME_A);
case 1:
return MyListFragment.newInstance(TAB_NAME_B);
case 2:
return MyListFragment.newInstance(TAB_NAME_C);
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return TOTAL_PAGES;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
You can access a particular page like this:
((MyListFragment) myPagerAdapter.getRegisteredFragment(0)).updateUI();
Where updateUI() is a custom method that updates your list on that page and calls notifyDataSetChanged().

How can make my ViewPager load only one page at a time ie setOffscreenPageLimit(0);

I understand the lowest number I can give setOffscreenPageLimit(int) is 1. but I need to load one page at a time because memory problems.
Am i going to have to use the old style tabhost etc? or is there a way/hack I can make my viewPager load one page at a time?
My Adapter extends BaseAdapter with the ViewHolder patern.
I was having the same problem and I found the solution for it:
Steps:
1) First Download the CustomViewPager Class from this link.
2) Use that class as mentioned below:
In Java:
CustomViewPager mViewPager;
mViewPager = (CustomViewPager) findViewById(R.id.swipePager);
mViewPager.setOffscreenPageLimit(0);
In XML:
<com.yourpackagename.CustomViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipePager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Now only one page will be loaded at once.
P.S: As per the question's requirement, I have posted the solution for Viewpager. I haven't tried the same with TabLayout yet. If I will find any solution for that I will update the answer.
In this file, KeyEventCompat is used it may not found by the android studio because KeyEnentCompat class was deprecated in API level 26.0.0 so you need to replace KeyEventCompat to event for more details you can view
https://developer.android.com/sdk/support_api_diff/26.0.0-alpha1/changes/android.support.v4.view.KeyEventCompat
As far as I know, that is not possible when using the ViewPager. At least not, when you want your pages to be swipe-able.
The explaination therefore is very simple:
When you swipe between two pages, there is a Point when both pages need to be visible, since you cannot swipe between two things when one of those does not even exist at that point.
See this question for more: ViewPager.setOffscreenPageLimit(0) doesn't work as expected
CommonsWare provided a good explaination in the comments of his answer.
but I need to load one page at a time because memory problems.
That presumes that you are getting OutOfMemoryErrors.
Am i going to have to use the old style tabhost etc?
Yes, or FragmentTabHost, or action bar tabs.
or is there a way/hack I can make my viewPager load one page at a time?
No, for the simple reason that ViewPager needs more than one page at a time for the sliding animation. You can see this by using a ViewPager and swiping.
Or, you can work on fixing your perceived memory problems. Assuming this app is the same one that you reported on earlier today, you are only using 7MB of heap space. That will only result in OutOfMemoryErrors if your remaining heap is highly fragmented. There are strategies for memory management (e.g., inBitmap on BitmapOptions for creating bitmaps from external sources) that help address such fragmentation concerns.
My Adapter extends BaseAdapter with the ViewHolder patern.
BaseAdapter is for use with AdapterView, not ViewPager.
I have an Answer for this. The above said method setUserVisibleHint() is deprecated and you can use setMaxLifecycle() method. For loading only the visible fragment you have to set the behaviour to BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT in the viewpager adapter. ie; in the Constructor. And for handling the fragment use onResume() method in the fragment.
In this way you can load only one fragment at a time in the viewpager.
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
}
In Kotlin:
class MyAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT )
Also use with FragmentPagerAdapter (now deprecated) in same way
By using this method you can load one page at time in tab layout with view pager`
#Override
public void onResume() {
super.onResume();
if (getUserVisibleHint() && !isVisible) {
Log.e("~~onResume: ", "::onLatestResume");
//your code
}
isVisible = true;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isVisible) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//your code
}
}, 500);
}
}
`
Override the setUserVisibleHint and add postDelayed like below in your every fragments.
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
if (isVisibleToUser)
Handler().postDelayed({
if (activity != null) {
// Do you stuff here
}
}, 200)
super.setUserVisibleHint(isVisibleToUser)
}
I can manage by this way and its working fine now for me.
First, copy in the SmartFragmentStatePagerAdapter.java which provides the intelligent caching of registered fragments within our ViewPager. It does so by overriding the instantiateItem() method and caching any created fragments internally. This solves the common problem of needing to access the current item within the ViewPager.
Now, we want to extend from SmartFragmentStatePagerAdapter copied above when declaring our adapter so we can take advantage of the better memory management of the state pager:
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
// Sparse array to keep track of registered fragments in memory
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Register the fragment when the item is instantiated
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
// Unregister when the item is inactive
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
// Returns the fragment for the position (if instantiated)
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
// Extend from SmartFragmentStatePagerAdapter now instead for more dynamic ViewPager items
public static class MyPagerAdapter extends SmartFragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return FirstFragment.newInstance(0, "Page # 1");
case 1: // Fragment # 0 - This will show FirstFragment different title
return FirstFragment.newInstance(1, "Page # 2");
case 2: // Fragment # 1 - This will show SecondFragment
return SecondFragment.newInstance(2, "Page # 3");
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
You actually don't need a custom ViewPager.
I had the same issue and I did like this.
Keep the setOffscreenPageLimit() as 1.
Use fragment's onResume and onPause lifecycle methods.
Initialize and free-up memories on these lifecycle methods.
I know this is an old post, but I stumbled upon this issue and found a good fix if your loading fragments. Simply, check if the user is seeing the fragment or not by overriding the setUserVisibleHint(). After that load the data.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
getData(1, getBaseUrl(), getLink());
}
}

Categories

Resources