How to get Current Fragment class instance from Activity? - android

Activity1 placed with fragment and starting activity2 by action item after closing activity2 i need to get a fragment instance of current fragment placed in activity1? thanks in advance

Your question does not give enough details, but I will assume you have an activity with multiple fragments. Also let us assume you are using tabs for navigation.
To get an instance of a fragment you can make use of tags assigned to each fragment. Here is the function that returns the tag associated with a fragment:
private static String makeFragmentName(int viewId, int position)
{
return "android:switcher:" + viewId + ":" + position;
}
And you would get the fragment like this:
MyFragment fragment = ((MyFragment) fm.findFragmentByTag(makeFragmentName(R.id.pager,position)))
Where R.id.pager is the pager view containing the fragments (with tabs), and position is the position of the fragment in a tab layout.
Let me know how this works out for you.

Related

How to call fragment's method from activity Android?

I have this kind of structure
MainPage Activity1 has view pager holding 3 fragments
I am using tabapdater
The first of the fragments have method to move to another Activity2
I want to fire some method in the first fragment when button is clicked in Activity2
Can i do that? can you guys give me any example code for it??
Thanks guys
There are some solutions.
The first one I think is startActivityForResult. If you start your second activity by calling startActivityForResult instead of startActivity you can expect the result in first activity by overriding the onActivityResult method and then change the first fragment content from there.
Another good and easy solution is using Buses like EventBus and otto.
They are well documented.
In your Fragment class:
public void foo(Object objectToPassFromActivity) {
// do what you want
}
In Your activity:
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag(getFragmentTag(R.id.yourViewPagerId, fragmentPosition);
fragment.foo(objectToPassFromActivity)
Add method:
private String getFragmentTag(int viewPagerId, int fragmentPosition) {
return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
}
You can see the link that i added in comments to get more details.

I've got a weird bug when using a ViewPager inside a Fragment

Okay i'll try and make this as clear as possible. I have a Fragment called CheckerManager which contains a ViewPager. This ViewPager will allow the user to swipe between 3 Fragments all of which are an instance of another Fragment called CheckerFragment. I'm using a FragmentPagerAdapter to handle paging. Here's how it looks
private class PagerAdapter extends FragmentPagerAdapter {
CharSequence mTabTitles[];
public PagerAdapter(FragmentManager fm, CharSequence tabTitles[]) {
super(fm);
mTabTitles = tabTitles;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return CheckerFragment.newInstance(MainFragment.DRAW_TITLE_LOTTO);
case 1:
return CheckerFragment.newInstance(MainFragment.DRAW_TITLE_DAILY);
case 2:
return CheckerFragment.newInstance(MainFragment.DRAW_TITLE_EURO);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return mTabTitles[position];
}
#Override
public int getCount() {
return 3;
}
}
I know that the ViewPager will always create the Fragment either side of the current Fragment. So say my 3 CheckerFragments are called A, B and C and the current Fragment is A. B has already been created. But my problem is that even though I am still looking at Fragment A, Fragment B is the 'active' Fragment. Every input I make is actually corresponding to Fragment B and not A. The active Fragment is always the one which has been created last by the ViewPager.
I've looked at quite a few things to see if anyone has had the same problem but i'm finding it difficult to even describe what's wrong. I think it's something to with the fact that all of the ViewPagers fragments are of the same type ie - CheckerFragment. I have a working implementation of a ViewPager inside a fragment elsewhere in the application and the only difference I can tell is that each page is a different type of Fragment.
Any help would be appreciated!
*EDIT
PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), tabTitles);
ViewPager viewPager = (ViewPager)view.findViewById(R.id.viewPagerChecker);
viewPager.setAdapter(adapter);
I feel pretty stupid but I found out what the issue was. In my CheckerFragment I would call getArguments() to retrieve a String extra and I would use this to determine how to layout the fragment. Problem was I made this extra a static member of CheckerFragment. So every time a new Fragment was created it was using the most recent extra.
Moral of the story - Don't make your fragments extra a static member if you plan on making multiple instances of that fragment.

findFragmentByTag() returns null only on the third tab of the ActioBar

I am using a tabbed Activity provided by Android with android.support.v7.app.ActionBar.TabListener,ViewPager and FragmentPagerAdapter. The parent Activty cointains and manages three Fragment. In addition, the parent Activity has a method to save the data provided by the fragments. In order to get the data defined in them (and not sended by the parent Activity) I am wrote the following code:
MyFragment frag = (MyFragment) mSectionsPagerAdapter.getActiveFragment(mViewPager,1,getSupportFragmentManager());
Where getActiveFragment() is
public Fragment getActiveFragment(ViewPager container, int position, FragmentManager mFragmentManager) {
String name = makeFragmentName(container.getId(), position);
return mFragmentManager.findFragmentByTag(name);
}
private String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
Actually, I have the following problem: when I try to save data provided by the three fragment, I have a java.lang.NullPointerException caused by the third fragment which is null. This happens only if I do not display on my device the second or third fragment.
I do not understand how to avoid and fix this behaviour.
Any suggestion?
This is due to the third fragment not being created if only the first tab/fragment is shown.
The ViewPager per default internally prepares the visible fragment, the one left to it and the one right to it.
Try
viewpager.setOffscreenPageLimit(2)

Get fragment object in activity while using viewPagerviewpager

Recently, I was trying to know How to swipe through fragments using a ViewPager. I have to set text on a TextView which is in Fragement from the activity. I found that one can get the Fragment object from ViewPager using :
getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":0");
When I tried to do this in onCreate() method of activity, it always returns null. I assume that is because Fragment is not started yet. Then in which method I should try to access the fragment object so that I can send arguments to the fragment methods?
This two answer SOLVE my problem.
ANSWER 1:
Fragment fragment = getSupportFragmentManager().getFragments().get(position);
OR ANSWER 2:
Fragment fragment = (Fragment) viewPager.getAdapter().
instantiateItem(viewPager, viewPager.getCurrentItem());
If you have a ViewPager and you want to access to a fragment which is inside a ViewPager, you can use this code:
Fragment currentFragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem()); //gets current fragment
//now you have to cast it to your fragment, let's say it's name is SenapatiFragment
((SenapatiFragment)currentFragment).someMethod(...); // you have now access to public fields and methods that are inside your fragment

How to notify all fragments in ViewPager that one of them changed?

My FragmentActivity contains ViewPager with some pages. Once one page is modified, others need to receive notification.
So my steps:
1. Send notification from fragment to activity
2. Getting list of fragments
3. Call notify to each one.
The problem is in step 2, to get fragments.
Calling adapter.getItem(int i) calls MyFragmentAdapter.getItem(int i), which returns new Fragment, that is not attached to activity.
Any ideas?
Adding next methods to YourFragmentPagerAdapter solves the problem:
public Fragment getActiveFragment(ViewPager container, int position) {
String name = makeFragmentName(container.getId(), position);
return mFragmentManager.findFragmentByTag(name);
}
private static String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
Why not just send out a broadcast from the Fragment that has changed and then have a broadcast receiver in your other fragments that receive the broadcast?

Categories

Resources