I haven\'t found something like setTag(String tagName) method in the Fragment class. The only way to set a Fragment tag that I have fo
This is the best way I have found :
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Let's first dynamically add a fragment into a frame container
getSupportFragmentManager().beginTransaction().
replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
commit();
// Now later we can lookup the fragment by tag
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentByTag("SOMETAG");
}
}
}
Nowadays there's a simpler way to achieve this if you are using a DialogFragment (not a Fragment):
val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
activity.supportFragmentManager,
"YOUR_TAG_FRAGMENT"
)
Under the hood, the show() method does create a FragmentTransaction and adds the tag by using the add() method. But it's much more convenient to use the show() method in my opinion.
You could shorten it for Fragment too, by using a Kotlin Extension :)
You can set tag to fragment in this way:
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.replace(R.id.MainFrameLayout,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
.addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit();
Yes. So the only way is at transaction time, e.g. using add, replace, or as part of the layout.
I determined this through an examination of the compatibility sources as I briefly looked for similar at some point in the past.
I know it's been 6 years ago but if anyone is facing the same problem do like I've done:
Create a custom Fragment Class with a tag field:
public class MyFragment extends Fragment {
private String _myTag;
public void setMyTag(String value)
{
if("".equals(value))
return;
_myTag = value;
}
//other code goes here
}
Before adding the fragment to the sectionPagerAdapter set the tag just like that:
MyFragment mfrag= new MyFragment();
mfrag.setMyTag("TAG_GOES_HERE");
sectionPagerAdapter.AddFragment(mfrag);
You can also get all fragments like this:
For v4 fragmets
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
For app.fragment
List<Fragment> allFragments = getFragmentManager().getFragments();