In Android, you can set a tag for a Fragment in a FragmentTransaction.
Why would I need to set a tag for a Fragment?
And is it good practice if a Fragment ch
Why would I need to set a tag for a Fragment?
Sometimes the Fragment
can be used as a background worker by the Activity
. Such fragment doesn't have UI, it is also called non-UI fragment. The String tag
is the only way to identify this fragment. To add this fragment, you use add(Fragment, String)
method which doesn't take View Id
. For example:
FragmentManager fm = getFragmentManager();
workFragment.setTargetFragment(this, 0);
fm.beginTransaction().add(workFragment, "work").commit();
Then later, to get the reference to this fragment use,
workFragment = (WorkFragment)fm.findFragmentByTag("work");
Now using the workFragment
reference you can access all the methods of this fragment in the Activity
or it's UI fragment. Here's the complete example of a non-UI fragment.
And is it good practice if a Fragment changed its behaviour based on its tag?
There are situations where we have to change the fragment's behaviour from Activity
using tags. It should be alright to do so, I've seen some open source apps using this practice. Basically you supply string tags to fragments. This is used for tagging a fragment within the FragmentManager
so we can easily look it up later. And change or access it's behaviour from the Activity
.
For example:
A user switches to SettingsActivity
from MainActivity
, changes the setting, presses back button to come back to MainActivity. You can detect the setting change in MainActivity#onResume() and update or change the behaviour of the current fragment according to the new setting.
FragmentManager fm = getFragmentManager();
uiFragment = (UiFragment) fm.findFragmentByTag("ui");
uiFragment.fetchNewData();
uiFragment.displayNewData();
Fragment tags can be used to avoid recreating a Fragment
on Activity
orientation change.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_image_pager);
MyFragment fragment;
if (savedInstanceState != null) {
fragment = (MyFragment) getFragmentManager()
.findFragmentByTag("my_fragment_tag");
} else {
fragment = new MyFragment();
fragment.setArguments(getIntent().getExtras());
getFragmentManager()
.beginTransaction()
.add(android.R.id.content, fragment, "my_fragment_tag")
.commit();
}
}
The Activity
is recreated on orientation change, and its onCreate(...)
method is called. If the Fragment
was created before the Activity
was destroyed and was added to the FragmentManager
with a tag, it can now be retrieved from the FragmentManager
by the same tag.
For a longer discussion on how it can be used, see: