不要使用android原生包中的Fragment
1 Fragment的作用是什么?
- 解决不同分辨率终端设备的适配问题。
- 模块化、可重用、可适配
2 Fragment VS Activity
- Fragment是Android 3.0+之后才出现的
- 一个Activity可以运行多个Fragment
- Fragment不能脱离Activity而存在
- Activity是屏幕的主题,而Fragment是Activity的一个组成元素
3 Fragment的加载方式——静态加载VS动态加载
3.1 静态加载——xml
- 创建一个Fragment类,用于显示列表。其中最重要的为
onCreateView
方法,该方法用于创建视图,渲染,并返回
public static class ListFragment extends Fragment {
// 创建视图
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// 参数1:布局文件;参数2:当前的ViewGroup;参数3:是否绑定到当前的根布局;
// 创建完成后将此view返回
View view = inflater.inflate(R.layout.my_fragment, container, false);
return view;
}
}
- 在布局文件中直接加载创建好的ListFragment类。例如我们可以创建一个新的布局,并加入
fragment
标签,其中android:name="com.example.fragment.ListFragment"
指向刚才创建的Fragment类。 - 可重用是指,我们可以重复使用,如下所示,可以将同一个Fragment放置在同一个activity中多次。
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context=".MainActivity">
<fragment
android:id="@+id/static_fragment"
android:name="com.example.fragment.ListFragment"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true" />
<fragment
android:id="@+id/static_fragment1"
android:name="com.example.fragment.ListFragment"
android:layout_width="200dp"
android:layout_height="200dp" />
</RelativeLayout>
- 如果要使用Fragment中的控件,不能直接使用
findViewById
,而是要使用刚才创建出来的view来寻找控件,例如view.findViewById
- 必须加入
id
和name
属性
3.3 动态加载——Java代码
- 步骤1:创建
container
,即Fragment
的摆放位置,可以通过在布局文件中添加布局来实现。 - 步骤2:在
MainActivity
中new
一个Fragment
ListFragment listFragment = new ListFragment();
- 步骤3:放置
Fragment
getSupportFragmentManager()
.beginTransaction() // 开启事务
.add(R.id.list_container, listFragment) // 将Fragment放到指定的container中
.commit(); // 提交事务
如果需要将同一个Fragment多次放置,则每次都需要重新new一个Fragment对象,因为一个Fragment只能与一个container关联。
4 Fragment传值
4.1 Activity → Fragment
- 在
Activity
中创建Fragment
时使用setArguments
传值。例如,可以使用如下方法创建Fragment
对象
public static ListFragment newInstance(String title) {
ListFragment fragment = new ListFragment();
Bundle bundle = new Bundle();
bundle.putString(BUNDLE_TITLE, title);
fragment.setArguments(bundle);
return fragment;
}
- 那么在
Fragment
的onCreate
方法中就可以获取到该值
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
title = getArguments().getString(BUNDLE_TITLE);
}
}
- 最后就可以在
Fragment
的onCreateView
中使用该值
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
TextView textview = view.findViewById(R.id.textView2);
textview.setText(title);
return view;
}
4.2 Fragment → Activity
- 使用回调方法??