In the developers's guide, it's said that a Fragment
can be added programmatically at r开发者_Go百科un time to an existing ViewGroup
. My question is : how is this ViewGroup
linked to the application?
So far, I have tried to declare a ViewGroup
in the xml files describing the layout of my application. But when I try to add a Fragment
to it by using the public abstract FragmentTransaction add (int containerViewId, Fragment fragment, String tag)
function, my application crashes (not immediatly but at the end of the onCreate
function of my application).
What I actually want to do is manage several views (implemented as Fragment
) in my application and to switch between them according to the user's choices. What should I add (or change) in my approach?
Thanks in advance for the time you will spend trying to help me.
ViewGroup can be simple frame layout
<FrameLayout
android:id="@+id/fragmentForChange"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Then for replace this frame with you fragment you need do nex:
Bundle args = new Bundle();
// add needed args
//create fragment and set arguments
Fragment fragment= MyFragment();
fragment.setArguments(args)
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// getSupportFragmentManager - uses for compatible library instead of getFragmentManager
//replace frame with our fragment
ft.replace(R.id.fragmentForChange,fragment);
//set type of animation
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//finish transaction
ft.commit();
You can hide or show fragments in transaction with command:
ft.hide(fragment);
ft.show(fragment);
I don't know what the reason of your crash may be, as you provided no details, just sending you a tip (it worked for me, and it is not as obvious as the Fragment API is not too intuitive to use).
Keep in mind, that Fragment created in FragmentTransaction is not added immediately, but rather on its own discretion (later, probably when the UI Thread is not busy), so the Fragment's getView() call might return null for some time, which might be a cause for the crash.
It is not clear to me why Google designed it this way, as the rest of the API is synchronous and - that's even more confusing - if you create Fragment as a part of your XML layout (using inflater) it is created synchronously as well and getView always returns value.
This is possible workaround : if you create your ViewGroup as a part of anther layout inflation process, it might work for you.
精彩评论