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

时间:2014-05-23 14:22:50

标签: android listview android-fragments android-fragmentactivity

我写了一个Android应用程序,在listview上显示三个数据库表的内容。为此,我写了三个活动。但是由于平板电脑的观点,我决定使用片段代替活动来显示彼此相邻的两个第一个列表视图的内容。为此,我创建了一个用于管理片段的活动,并将我的自定义操作栏添加到onCreate方法,并且它在layout-large文件夹中具有相同的布局:

<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" />

并将以下内容作为布局文件夹上管理器片段的布局:

<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" />

之后我将第一个活动改为片段。只需将交换“扩展活动”扩展为“扩展片段”并将onCreate更改为片段的oCreate并在其上放置相同的指令,除了将布局置于以下方法的覆盖之外:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_index, container, false);
}

我认为我的片段使用了之前活动的布局。但是当我运行它时,我得到以下错误: 无法启动活动componentInfo..android.view.inflatEException:二进制XML文件行#8:错误膨胀类片段。 我搜索了这个错误,但没有一个答案对我没用,我得到了这个。有什么想法吗?我得到这个减去这个问题,请忽略它们,如果我以正确的方式提出我的问题,请删除它的减号。

1 个答案:

答案 0 :(得分:2)

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

例如: 你的活动onCreate()的代码应该在片段的onCreateView()中实现,当然你必须改变一些东西,如填充视图并返回它而不是调用setContentView( R.layout.id)。

也为onResume(),onStop(),onPause()等实现它。

然后你需要实现FragmentActivity并创建并附加这个片段(你可以从xml或代码中完成),你可以找到here如何做到这一点。