1

我正在尝试使用 Android 兼容性包来创建一个使用 Fragments 的向后兼容的应用程序。但是,当我在 Android v2.2 模拟器上运行它时它会崩溃。它不会在我的 Xoom (v3.2) 上崩溃。我怀疑 main.xml 中的片段标记可能是原因:

<?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>

这是片段活动:

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);
    }
}

这是片段:

package com.companyname.appname;

import android.support.v4.app.Fragment;

public class MainMenuFragment extends Fragment {

}

有任何想法吗?

谢谢

编辑:我的目标是 API 8 级(Android v2.2)

4

2 回答 2

2

谢谢,smith324 和 LeffelMania。错误 logcat 显示此错误:08-03 22:03:22.946: ERROR/AndroidRuntime(938): Caused by: java.lang.IllegalStateException: Fragment com.companyname.appname.MainMenuFragment 没有创建视图。所以我在我的 MainMenuFragment 类中覆盖了 onCreateView() 并让它返回一个视图,这很有效。奇怪的是它在 v3.2 中没有崩溃。

于 2011-09-22T18:59:27.840 回答
1

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.

于 2012-04-10T15:19:43.603 回答