0

嗨,我是 android 开发的新手。

我正在使用片段 - 但我不完全理解它是如何工作的。

当我启动应用程序时它崩溃了。

我用谷歌搜索了很多,但大炮解决了这个问题:(

我有一个必须使用片段的 Activity(MainActivity)。MainActivity 看起来像:

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

main.xml 包含一个 ListView 和一个 Fragment:

<ListView 
    android:id="@+id/myListView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<fragment class="com.todolist.NewItemFragment"
    android:id="@+id/titles_fragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

我的片段扩展了 ListFragment,看起来像:

public class NewItemFragment extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.new_item_fragment, container, false);
    }
}

new_item_fragment.xml 看起来像:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<ListView 
    android:id="@+id/myListView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

我不知道它为什么会崩溃。我一定是误会了什么。我希望那里有人可以提供帮助-不知道该怎么做:)

谢谢


我已经导入了库:

android.support.v4.app.FragmentActivity

并使 MainActivity 类扩展 FragmentActivity

它给了我以下错误:

在此处输入图像描述

4

2 回答 2

1

像这样修改new_item_fragment.xml布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<ListView 
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

解决最明显的错误。如果应用程序仍然崩溃,则发布Logcat异常。

此外,当您扩展Activity类时,请确保您只使用FragmentSDK 中的相关类(如果您在应用程序中注册了兼容性包,则不要使用它)。这些课程从Honeycomb.

如果您要使用FragmentActivity,请确保使用Fragment兼容性包中的类(来自哪里FragmentActivity)。

于 2012-12-03T12:36:13.750 回答
0

尝试用以下代码替换您的片段:

public class NewItemFragment extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.new_item_fragment, null, false);
    }
}
于 2012-12-03T12:43:24.147 回答