我正在开发一个包含活动的项目,我想将一些标签活动转换为片段

时间:2016-11-24 06:37:37

标签: android android-fragments android-activity

我想将HomeActivity转换为HomeFragment。我想用

 changefragment(new HomeFragment());

我该怎么办?请建议

1 个答案:

答案 0 :(得分:0)

您必须更改在活动中实例化视图的方式,并将其转移到片段。我个人的偏好是为片段创建一个新的类文件,并将其命名为Fragment,例如。 ListActivity = ListFragment

然后在活动onCreate方法中,正常setContentView:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

然后,您需要创建片段的实例并将其注入您在activity_list布局文件中创建的容器中:

ListFragment fragment = new ListFragment();
getSupportFragmentManager().beginTransaction()
                .add(R.id.activity_list_container, fragment)
                .commit();

将片段与活动类似地处理,除了在引用上下文时使用this,您使用getActivity()

以下是activity_list.xml布局文件的示例:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".ListActivity">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/activity_list_container"/>

    </android.support.design.widget.CoordinatorLayout>