1

I admit I am still struggling with Fragments and currently I don't know where to load what:

At first I loaded my Fragment in OnCreate() of my Activity, but then I had difficulty to access it (via findViewById) and moved it to onStart(), but I can't still find the Views within the Fragments on onStart()...

So in onCreate:

setContentView(R.layout.myfrag);
FrameLayout fl = (FrameLayout)findViewById(R.id.iPortraitView);  // different for Landscape
if(fl.getChildCount() == 0)  {
     getFragmentManager().beginTransaction()
    .add(R.id.iTestView, new AFragmentClass).commit();
}
else {
     getFragmentManager().beginTransaction()
    .replace(R.id.iTestView, new AFragmentClass).commit();
}
Log.d("myTest", String.valueOf(fl.getChildCount()));

Now the problem is that fl.getChildCount() always returns 0 in onCreate, thereby adding new Fragments, while actually there is something in there and when I call the same code (fl.getchildCount() ) in onCreate, I get the correct count (which obviously increases each time I change the orientation). And as a result I have overlapping Views from both my landscape and portrait layouts.

I'm a a loss here and guess I'm struggling with figuring out what to load when (and especially when I can access them). Furthermore, do I have to implement all Listeners for potential Views (like Buttons contained in the various Fragments) that I might load dynamically in my Fragments?

Markstar
  • 639
  • 9
  • 24
  • 2
    When you add your fragment in your activity, give it a String `TAG`, using the additional overload, `.add(R.id.iTestView, new AFragmentClass(), "AFragment").commit()`, that way later you can call `getFragmentManager.findFragmentByTag("AFragment")` and you will be able to access the fragment. You can also use the fragment ID as in this answer, http://stackoverflow.com/a/6751537/418505 – Selecsosi Jan 16 '14 at 16:24

1 Answers1

0

The Fragment's onCreateView() hasn't been called at that point in the Activity-Fragment life cycle. onCreate(Bundle bundle) is called before onCreateView(), so there would be no views to get the count of at that point of execution. See the lifecycle: http://developer.android.com/guide/components/fragments.html.

In order to set listeners, and other view modifications on your fragment, you need to overright the onCreateView() method within your fragment.

Submersed
  • 8,810
  • 2
  • 30
  • 38