繁体   English   中英

片段无法正常工作

[英]Fragment wont work

嗨,我是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

它给了我以下错误:

在此处输入图片说明

修改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所在的位置)。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM