Android 如何将现有活动转换为具有相同功能和布局的片段?

Android 如何将现有活动转换为具有相同功能和布局的片段?,android,listview,android-fragments,android-fragmentactivity,Android,Listview,Android Fragments,Android Fragmentactivity,我编写了一个android应用程序,在listview上显示三个数据库表的内容。为此,我写了三个活动。但由于tablet视图的缘故,我决定使用fragment而不是activity来显示两个第一个列表视图的内容。为此,我制作了一个用于管理片段的活动,并将我的自定义actionbar添加到onCreate方法中,它在布局大文件夹中具有布局,如下所示: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android

我编写了一个android应用程序,在listview上显示三个数据库表的内容。为此,我写了三个活动。但由于tablet视图的缘故,我决定使用fragment而不是activity来显示两个第一个列表视图的内容。为此,我制作了一个用于管理片段的活动,并将我的自定义actionbar添加到onCreate方法中,它在布局大文件夹中具有布局,如下所示:

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

<fragment
    android:id="@+id/poemlist"
    android:name="com.example.emampoems.poemTypeFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2" />

<fragment
    android:id="@+id/list"
    android:name="com.example.emampoems.Index"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />
我想我的片段使用了之前活动的布局。但当我运行它时,我得到以下错误: 无法启动activity componentInfo..android.view.inflatEException:二进制XML文件行#8:膨胀类片段时出错。
我在谷歌上搜索了这个错误,但没有一个答案对我没有用处,我得到了这个答案。你知道为什么吗?在回答这个问题之前,我得到了这个负号。请忽略它们。如果我以正确的方式提问,请删除它的负号。

您需要创建一个新片段,并将活动生命周期中的功能添加到片段的生命周期中

例如: 您的活动的onCreate()代码应该在片段的onCreateView()中实现,当然您必须更改一些内容,比如放大视图并返回它,而不是调用setContentView(R.layout.id)

对onResume()、onStop()和onPause()等也实现它


然后,您需要实现一个FragmentActivity并创建此片段并将其附加到它(您可以从xml或代码中执行),您可以了解如何执行此操作。

配置限定符是您应该查看的内容之一。ProTip:在创建应用程序之前,请阅读完整的开发者指南。感谢您的回答,网站上有一个文档。这很有帮助。我还有一个问题,但我不能用通常的方式问。这个片段是左/右的。有什么方法可以使它右/左吗?我不确定我是否理解你的意思。你能发布另一个问题并给我发送链接吗?对不起。我不能再加新问题,因为我有很多负数,需要先去掉负数。我的意思是我需要改变片段的位置,第一个片段加载在右侧,第二个片段加载在左侧
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<fragment
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.example.emampoems.Index" />
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_index, container, false);
}