Android : passing parameters to a tab
Asked Answered
P

2

6

In my Android app, I use the following code to create tabs :

mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
            MyFragment.class, null);

In the addTab method, the third parameter is a Bundle object and is null. Could I use this third parameter to pass parameters to my fragment ?

The android API documentation is empty for addTab and does not document this parameter.

Poulson answered 15/5, 2013 at 10:7 Comment(0)
E
10

The answer is yes. the parameters you are passing in this Bundle are later set as your fragment arguments and can be accessed with getArguments from inside the fragment.

The code that makes it happen in the FragmentTabHost is :

newTab.fragment = Fragment.instantiate(mContext,
                        newTab.clss.getName(), newTab.args);
Everett answered 15/5, 2013 at 10:16 Comment(7)
@Sean: What kind of object is newTab? I cannot get the fragment property from the FragmentTabHost.Ocotillo
@Ocotillo Hope I understood right your question. First, you should know you could always access your fragments via the same TAG you've initiated them in the tab host, with a simple getSupportFragmentManager().findFragmentByTag(TAG_OF_FRAGMENT) . If you wish to know what's the current fragment that is displayed in the tab host, use developer.android.com/reference/android/widget/… to fetch the TAG and then you can acccess the fragment as mentioned above. P.S. the "newTab" is an inner member of FragmentTabHost.Everett
@Sean: Ah ok. I guess I can't use it because it's an inner class.Ocotillo
@Ocotillo If you do wish to access it you can either copy the entire class code to your project / use reflectionEverett
The reason why I'm asking is I want to access the fragment I added in the TabHost later in the code or even use a custom constructor for the Fragment before adding it to the TabHost.Ocotillo
@Ocotillo 1. You can always access them with findFragmentByTag (use the tag you've assigned to the tab host). 2. If you wish to construct the fragment with some other parameters you can use the Arguments that are being sent. this, acting like a kind of an Intent with an Activity, will serve the purposeEverett
@Sean: I tried that but I'm getting null. I can't figure out which event those fragments will be ready.Ocotillo
W
1

Looking at the FragmentTabHost.java,looks like it passes this bundle to the tabinfo,which inturn has the fragment.So the answer is yes !

Wylma answered 15/5, 2013 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.