Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to start a Fragment hidden by defining it's state in the XML?

Tags:

android

Currently I'm defining a variety of Fragments in the resource file and hiding them in the containing Activity's onCreate method, but I'm not satisfied with this approach as I would expect this to be one of the characteristics that each fragment would define for itself.

Am I objectifying Fragments too much or just missing the technique ?

thanks, R

like image 286
pierre renoir Avatar asked Apr 04 '12 22:04

pierre renoir


People also ask

How do I show and hide a fragment?

From my code, comparing to above solution, the simplest way is to define a layout which contains the fragment, then you could hide or unhide the fragment by controlling the layout attribute which is align with the general way of view.

What is a fragment in XML?

A Fragment is a combination of an XML layout file and a java class much like an Activity . Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities.

How do I show fragments in activity XML?

You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.


1 Answers

I'm not satisfied with this approach as I would expect this to be one of the characteristics that each fragment would define for itself.

I disagree with that assessment.

Fragments are responsible for a small section of the screen and any events that are purely contained within that small section of the screen.

Whether the fragment is hosted Activity A or Activity B or Activity C, whether it is alongside other fragments or not, whether it is presently visible or not, and so on is not the fragment's responsibility. That responsibility lies with the hosting activity (or activities, if the fragment is reused). The hosting activity knows the screen size and what should be done in terms of loading particular fragments onto the screen.

After all, the rules may change. Perhaps the fragment is hidden on small/normal screens but visible on large/xlarge screens. Or, perhaps the fragment was initially used individually but later is loaded into a ViewPager. Or, perhaps the fragment is being dynamically created as part of a FragmentTransaction and added to the BACK stack, so the user can independently get rid of the fragment. IMHO, the fragment should neither know nor care about any of this stuff, as it all transcends the boundaries of that one individual fragment.

like image 183
CommonsWare Avatar answered Jan 03 '23 14:01

CommonsWare