【问题标题】:Fragment wont work片段不起作用
【发布时间】:2012-12-03 12:33:08
【问题描述】:

您好,我是 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

它给了我以下错误:

【问题讨论】:

  • 请发布您的 logCat。
  • 查看我在回答中所做的编辑。

标签: java android xml fragment


【解决方案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 类时,请确保您只使用 SDK 中的 Fragment 相关类(如果您在应用程序中注册了兼容性包,则不要使用它)。这些课程从Honeycomb开始提供。

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

【讨论】:

  • 我要在哪里使用 Fragment 类?
  • @user1093774 您使用ListFragment,因此请确保您的NewItemFragment 类扩展了兼容性包中的ListFragment。检查您的导入。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多