Can you build layouts inside of fragements in Honeycomb?
I'm a bit new to Android and very new to Fragments. I'm attempting to port an application from Activities to Fragments (well, Activities + Fragments) for Honeycomb. Before we get to the tablet screens, we want to have our app working with the Fragment Compatibility Library for 1.6+ devices. I've read the documentation and examples from Google an开发者_如何学God nothing explicitly says I can or cannot do the following, but it is not working for me.
The first screen ported is the launcher screen, which has a layout file called fragment_splash.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/splash_background">
<fragment class="...StartupFragmentLayout$StartupFragment"
android:id="@+id/fragStartup"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/debugText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="DEBUG ON"
android:gravity="center"
android:textSize="35sp"
android:textColor="@color/blue_text"
android:textStyle="bold"
android:shadowColor="#FFFFFF"
android:shadowRadius="2"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:gravity="bottom">
...
</fragment>
</LinearLayout>
However, this does not work. I get an error stating that StartupFragmentLayout$StartupFragment did not create a view. I'm beginning to suspect that I can't nest anything inside the <fragment>
, since I haven't seen it done in any documentation or examples. Is this correct, or is my problem something else?
It's not clear from the documentation whether you can have child views in a <fragment>
. Given none of the fragment samples do this then I suspect it is not the way that they are meant to be used. You could try changing <fragment>
into a <FrameLayout>
and adding the fragment into it at run-time if you really want to, to see if that works.
However, I think your best solution is to put your child views into a separate layout file and then in onCreateView
inflate into the fragment's container via say:
final View iv = inflater.inflate(R.layout.favourites, container, false);
I don't think that you will lose anything as a result of doing it this way.
Just to tie this off, fragments can not have children in layouts. PJL is suggesting the right approach. The layout inside a fragment should be specified in a separate XML file. You can then inject this layout into the view tree by returning it from the fragments onCreateView method.
精彩评论