1.在activity布局文件中加入fragment节点,加入android:name=”com.guo.fragment.MyFragment”属性,属性值是fragment的类全名
<RelativeLayout 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"
>
<fragment
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.guo.fragment.MyFragment"
android:layout_below="@id/textview"
/>
</RelativeLayout>
2.在activity代码中什么都不用写
3.新建一个类继承Fragment,重写里面的方法
package com.guo.fragment;
public class MyFragment extends Fragment {
/**
* 确定当前的fragment绑定的activity时回调
* */
public void onAttach(Activity activity) {
super.onAttach(activity);
}
/**
* fragment被创建时
* */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* fragment加载自己显示的视图时,这个方法必须重写
* */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 加载自己实现的视图
View view = inflater.inflate(R.layout.my_fragment, null);
return view;
}
}
4.创建fragment的布局视图
<RelativeLayout 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"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="fragment页面" />
</RelativeLayout>