Get fragment object in activity while using viewPagerviewpager - android

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

Related

onCreateView from Fragment not called

I am refactoring an Android App to use fragments. I have a fragment which I add to the layout with transaction.replace method but whose onCreateView method is not called. Code looks as follows:
FragmentManager fragmentManager = m_Activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
m_StartNewGameFragment = new StartNewGameToggleButtonsFragment();
fragmentTransaction.replace(R.id.bottom_pane, m_StartNewGameFragment);
fragmentTransaction.commit();
String winnerText = null;
if (isComputerWinner)
winnerText = m_Activity.getResources().getText(R.string.computer_winner).toString();
else
winnerText = m_Activity.getResources().getText(R.string.player_winner).toString();
m_StartNewGameFragment.updateStats(computerWins, playerWins, winnerText);
The method updateStats of fragment is as follows:
public void updateStats(int computer_wins, int player_wins, String winnerText) {
System.out.println("Update stats " + m_ComputerWins);
m_ComputerWins.setText(Integer.toString(computer_wins));
m_PlayerWins.setText(Integer.toString(player_wins));
m_WinnerTextView.setText(winnerText);
}
When updateStats is called m_ComputerWins is null and the program crashes. m_ComputerWins is initialized inside the onCreateView method of the fragment which seems not to be called.
Can anyone please help ?
Take global variables in your fragment class for computer_wins, player_wins, winnerText and init them inside updateStats method.
then inside onViewCreated() method, set values like
m_ComputerWins.setText(Integer.toString(computer_wins));
m_PlayerWins.setText(Integer.toString(player_wins));
m_WinnerTextView.setText(winnerText);
You never know when the fragments is created (which calls onCreate()), because fragment's life cycle differs from your activity's. In your code, you are trying to update fragment from activity. But in the way you have written your code, it is almost guaranteed that your fragment is not created yet.
Search for how to pass parameters to fragment or update fragment to find out the correct way of updating fragment from activity. You can find several related question, e.g. this one.
FragmentTransaction only runs on the next event loop. If you want to immediately run a fragment transaction, use fragmentTransaction.commitNowAllowingStateLoss();.
Please note that this won't actually work correctly after process death, which is why you should use the fragment.setArguments(Bundle method to pass initial argument values to a fragment.

Alternative of findFragmentById for getting a reference of already open fragment

Im trying to tell a fragment to change a certain view's visibility from the activity, but I dont know how to get a reference to that fragment.
What I found is
findFragmentById(R.id.asdasd)
But my fragment is not inflated from an XML layout so it doesnt have such an ID (I guess?)
So how can I reference this fragment in another way?
Here is how I add the fragment from the activity:
public void addFragment(Fragment fragment) {
String fragmentClassName = ((Object) fragment).getClass().getSimpleName();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.fragment_container, fragment, fragmentClassName);
t.addToBackStack(fragmentClassName);
t.commit();
Since you already set the tag in your fragment you can use it to find the fragment by its tag using the Fragment Manager.
sample:
String fragmentClassName = The_Class_Name_Of_Fragment.getClass().getSimpleName();
YourFragment fragment = getFragmentManager().findFragmentByTag(fragmentClassName);
You should call findFragmentById(R.id.fragment_container) to reference your Fragment.

How to get Current Fragment class instance from Activity?

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.

getTag method in fragment return null

I try to use FragmentActivity with single Fragment without viewpager and others.
I need the tag value from Fragment with the getTag method...
My code in onCreate of FragmentActivity :
// launch splash screen fragment
Fragment fragment = SplashScreenFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit();
And when SplashScreenFragment is onCreateView, getTag() method return null in fragment..
I don't understand this .. I don't use Fragment attribut in XML layout, that is a reason ?
EDIT ::
I need tag to execute this code :
this.mSplashScreenFragment = (SplashScreenFragment) mMainFragmentActivity.getSupportFragmentManager().findFragmentByTag(tag);
mSplashScreenFragment after this line is null ..
Thank you for help !
For ability to access fragment tag you should use
FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
method when you want to add fragment. In other words you should first set this tag from anywhere

how to identify the current fragment?

My question is not easy to describe, but I will do my best:
On my tablet-app I have one activity with a listFragment A on left side and a detailFragment B on right side. So when I click an item on the list, the detailFragment shows the proper details of the chosen (list) item.
Now when I click a button on my detailFragment B. the fragment gets swapped with a new Fragment from type infoFragment. The listFragment on left side stays as it is.
So now, when I click another item on the List, I want the infoFragment to vanish and get a detailFragment once again.
My problem is, that i need some kind of check if currently there is an infoFragment or a detailFragment displayed. So that I can either just refresh the detailFragment OR stop the infoFragment and build a new detailFragment.
idea:
if ( //detailFragment is active ) {
updateContent();
}
else {
FragmentManager.buildDetailFragment();
}
have been fiddling for hours now, any help is appreciated!!
How can i figure it out whether there is a detailFragment or listFragment displayed?
edit:
i change my detailFragment with the infoFragment here:
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.details_fragment);
fragment = new InfoFragment();
fm.beginTransaction()
.replace(R.id.details_fragment, fragment)
.commit();
When you add a Fragment to your fragment manager with a FragmentTransaction you can specify a key value. You can then findFragmentByTag which will determine if the Fragment with that key value has been added to the fragment manager.
So long as you are not using a ViewPager or some other structure where multple fragments are added at once, searching for whether your fragment manager contains a fragment by tag will let you know which is currently displayed. You can then use the results of that search to update the fragment since the result is a reference to the fragment itself.
This means you can pass data from the FragmentActivity to the fragment directly by calling any publicly accessable fragment methods. For example
Fragment displayedFragment = fragmentManager.findFragmentByTag(TAG);
if(displayedFragment != null){ //null if no fragment with tag value
displayedFragment.updateList() //public method within fragment
}
MyFragment myFragment = (MyFragment)getFragmentManager().findFragmentByTag("MY_FRAGMENT");
if (myFragment.isVisible()) {
// add your code here
}
From Here
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content_id);
now we can get the fragment name by getClass
fragment.getClass().getSimpleName()
You can get class of fragment and check which one it exactly is by calling getClass().

Categories

Resources