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>
本文介绍了如何在Android中实现静态加载Fragment。首先,在Activity的布局文件中通过添加Fragment节点并指定类全名来配置。然后,只需创建一个新的Fragment类,继承自Fragment,并实现其所需方法。最后,为Fragment设计相应的布局视图。在整个过程中,Activity的代码无需额外处理。
252

被折叠的 条评论
为什么被折叠?



