首先声明三点:
1、在需要嵌套Fragment的activity必须继承android.support.v4.app.FragmentActivity
2、嵌套的Fragment必须继承android.support.v4.app.Fragment
3、此教程仅适用于新手或者老手查阅
先上一个目录结构:
步骤:
1、新建一个嵌套fragment的activity:MainAcitivity.java和对应的布局文件main_activity.xml
main_activity.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.ruan.app.MainActivity"> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1"></FrameLayout> </LinearLayout>
MainAcitivity.java
package com.ruan.app; import android.support.v4.app.FragmentActivity; import android.os.Bundle; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); //必需继承FragmentActivity,嵌套fragment只需要这行代码 getSupportFragmentManager().beginTransaction().replace(R.id.container, new MyFragment()).commitAllowingStateLoss(); } }
2、新建一个需要嵌套的Fragment:MyFragment.java和对应布局文件my_fragment.xml
my_fragment.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#ffffff" android:textSize="48dp" android:text="myfragment"/> </RelativeLayout>
MyFragment.java
package com.ruan.app; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.my_fragment, null); } }
好,完事 运行,下面是效果图
代码下载地址:http://pan.baidu.com/s/1hr8FYLI