Android: compatibility package Fragment crash
I am trying to use the Android compatibility package to create a backwards-compatible app that uses Fragments. However, it crashes when I run it on an Android v2.2 emulator. It does not crash on my Xoom (v3.2). I suspect the fragment tag in the main.xml might be the cause:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<fragment android:name="com.companyname.appname.MainMenuFragment"
android:id="@+id/mainMenu"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent" />
</LinearLayout>
Here is the FragmentActivity:
package com.companyname.appname;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class AppName extends FragmentActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
And here开发者_如何学编程 is the Fragment:
package com.companyname.appname;
import android.support.v4.app.Fragment;
public class MainMenuFragment extends Fragment {
}
Any ideas?
Thanks
EDIT: I have targeted API level 8 (Android v2.2)
Thanks, smith324 and LeffelMania. The error logcat showed this error: 08-03 22:03:22.946: ERROR/AndroidRuntime(938): Caused by: java.lang.IllegalStateException: Fragment com.companyname.appname.MainMenuFragment did not create a view. So I overrode onCreateView() in my MainMenuFragment class and had it return a View, and this worked. Strange that it didn't crash in v3.2.
Sometimes you doesn't want an UI to be attached to your Fragment. For example in my app I have a fragment responsible for a menu item used as an action view in the action bar. In this case you can't implement onCreateView()
.
As described in the Android Fragment user guide in the "Adding a fragment without a UI" section, you have to add the fragment to his activity programmatically.
Here is the code I use in my activity :
// Add the address bar fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(addressBarFragment,"address_bar_fragment");
fragmentTransaction.commit();
Note 1: I use getSupportFragmentManager()
instead of getFragmentManager()
because I use the compatibility library.
Note 2: new Fragment() is not called in my example because I use Roboguice for dependences injection.
精彩评论