一、创建
/** * 创建和使用fragment的步骤 * 1、创建子类继承与fragment * 2、重写onCreate()方法,该方法主要定义fragment的布局,以view对象的形式返回fragment的视图 * 3、将fragment引入到Activity中 */ public class TitleFragment extends Fragment { /** 表示fragment第一次创建绘制用户界面时系统回调的方法 返回view表示当前加载fragment视图,如果fragment不提供视图可以返回null LayoutInflater inflater,表示当前布局填充器或者加载器,将xml文件转换成view对象 ViewGroup container, 表示当前fragment插入activity的布局视图对象 Bundle savedInstanceState,表示存储上一个fragment的信息 */ @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // 将xml文件转换成具体的view对象 View view = inflater.inflate(R.layout.fragment_title, null); RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.rl_layout); layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "我是标题", Toast.LENGTH_SHORT).show(); } }); return view; } }
二、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:id="@+id/rl_layout"> <ImageView android:id="@+id/iv_bavk" android:layout_width="35dp" android:layout_height="35dp" android:layout_centerVertical="true" android:paddingLeft="15dp" android:scaleType="centerCrop" android:src="@mipmap/ic_launcher"/> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:textSize="20sp" android:text="标题" android:layout_centerInParent="true" android:textColor="#ffffff"/> </RelativeLayout>
三、引用页面的xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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" tools:context="com.mycompany.fragment.MainActivity"> <!--android:name="表示获取fragment的包名.类名"--> <fragment android:id="@+id/fragment_title" android:layout_width="match_parent" android:layout_height="50dp" android:name="com.mycompany.fragment.TitleFragment"/> <fragment android:id="@+id/fragment_content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/fragment_title" android:name="com.mycompany.fragment.ContentFragment"/> </android.support.constraint.ConstraintLayout>
动态添加
// fragment动态实用 // 1、创建Fragment的管理对象 // 非v4包下的 // FragmentManager manager = getFragmentManager(); // v4包下的 继承方式改为FragmentActivity FragmentManager manager = getSupportFragmentManager(); // 2、获取fragment的十五对象并开启事务 FragmentTransaction transaction = manager.beginTransaction(); // 3、调用事务中相应的的动态操作fragment的执行方法,add(表示fragment动态添加位置的资源id,第二个表示添加的fragment对象) transaction.add(R.id.title_layout, new TitleFragment); // 动态添加layout位置 // transaction.remove(agr0); 删除 // transaction.replace(arg0, arg1); 替换 // 4、提交事务 transaction.commit();