Fragment的基本使用
创建Fragment
新建MyFragment类继承Fragment。**注意是v4包(android.support.v4.app.Fragment)**的Fragment。
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//加载布局
View view = inflater.inflate(R.layout.my_fragment,null);
//......
return view;
}
}
然后新建布局文件。这里注意设置tools:tools:context=".Fragment.MyFragment"
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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=".Fragment.MyFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是MyFragment里面的内容" />
</FrameLayout>
静态加载Fragment
这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中,用布局文件调用Fragment。这里要注意的是fragment要设置name属性,指定Fragment。看例子:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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:name="com.example.cai.a20181128code_fragment.Fragment.BlankFragment"
android:layout_weight="1"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
<fragment
android:name="com.example.cai.a20181128code_fragment.Fragment.MyFragment"
android:layout_weight="1"
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
动态使用Fragment
举个例子,先修改MainActivity界面,这里弄了两个按钮来切换不同的Fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:text="btn_1"
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="40dp" />
<Button
android:text="btn_2"
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="40dp" />
<FrameLayout
android:id="@+id/holder"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
修改Activity中的代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Fragment管理器
fragmentManager = getSupportFragmentManager();
//开启事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//添加一个Fragment
fragmentTransaction.add(R.id.holder,new MyFragment());
//提交事务
fragmentTransaction.commit();
findViewById(R.id.btn1).setOnClickListener(this);
findViewById(R.id.btn2).setOnClickListener(this);
}
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (v.getId()){
case R.id.btn1:{
//修改Fragment
fragmentTransaction.replace(R.id.holder,new MyFragment());
break;
}
case R.id.btn2:{
fragmentTransaction.replace(R.id.holder,new BlankFragment());
break;
}
}
fragmentTransaction.commit();
}
}
上面的代码,首先在Activity执行onCreate的时候动态载入了一个初始Fragment,然后在两个按钮的点击事件中对Fragment进行了动态修改。
FragmentTransaction的使用
上面实现动态加载使用了FragmentTransaction。除了add()以外,它还有几个关键的用法:
- replace
- remove
- addToBackStack
replace
replace一看就知道是替换了。但是它不是指定某个fragment然后替换为另外一个。他接受两个参数(布局id、Fragment对象)
如果你的xml文件里面已经有了几个fragment的话,那么你调用replace等于直接添加一个进去
而如果你使用动态添加的做法,add了几个fragment进去,replace则会将add进同一个布局里面全部删除,然后放一个指定的进去。
举个例子,在布局A里面add了FragemenA和FragmentB,此时调用replace,换入FragmentC,那么FragemenA和FragmentB会依次执行销毁部分的生命周期,最后走到onDetach完全消失。
remove
remove和replace一样,对写在xml里面的Fragment也是无能为力,但是如果是add的,或者replace的是可以的。和上面的逻辑一样,就不赘述了。
addToBackStack
上面的来呢方法导致了这样的一个问题。不论是replace还是remove,之前的fragment就直接没了,走了销毁的生命周期。试想这样一个场景。刚开始add进去一个fragment,和用户交互一会,然后需要replace另外一个,所以自然的调用了replace方法,再交互一会又需要换回到原来那个,这个时候注意,换回的原来的那个应该是和之前一样的,保存有自己数据的那个。这个时候addToBackStack就起到了作用。
Fragment中的点击事件
值得注意的是,在onCreateView中不能直接进行点击事件,需要放到onActivityCreated()中:
onCreateView():每次创建、绘制该Fragment的View组件时回调该方法,Fragment将会显示该方法返回的View组件。
onActivityCreated():当Fragment所在的Activity被启动完成后回调该方法。访问父activity的view层的时候需要在onActivityCreated 方法里面做
public class BlankFragment extends Fragment {
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.blank_fragment,null);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//我在XML文件中加了一个按钮
Button button = getActivity().findViewById(R.id.fragmentBtn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "别点了!", Toast.LENGTH_SHORT).show();
}
});
}
}
Fragment的生命周期
上一张官方图,左边的是Activity的生命周期,右边是Fragment,与之对比就很好理解
1.onAttach()
fragment已经关联到activity,这个时候 activity已经传进来了, 获得activity的传递的值 就可以进行 与activity的通信里, 当然也可以使用getActivity(),前提是这个fragment已经和宿主的activity关联,并且没有脱离,有且只有调用一次。
2.onCreate()
系统创建fragment的时候回调他,在他里面实例化一些变量,这些个变量主要是:当你暂停或停止的时候,你想保持的数据。这个方法只调用一次。
3.onCreateView()
第一次使用的时候 fragment会在这上面画一个layout出来, 为了可以画控件 要返回一个 布局的view,也可以返回null j 就什么都没有显示。
当系统用到fragment的时候 fragment就要返回他的view,越快越好 ,所以尽量在这里不要做耗时操作,比如从数据库加载大量数据
4.onActivityCreated()
当Activity中的onCreate方法执行完后调用。
当执行onActivityCreated()的时候 activity的onCreate才刚完成。所以在onActivityCreated()调用之前 activity的onCreate可能还没有完成,所以不能再onCreateView()中进行与activity有交互的UI操作,UI交互操作可以在onActivityCreated()里面进行。
5.onStart()
和activity一致,启动Fragement 启动时回调,,此时Fragement可见。
6.onResume()
和activity一致 在activity中运行是可见的。激活, Fragement 进入前台, 可获取焦点时激活。
7.onPause()
和activity一致 其他的activity获得焦点,这个仍然可见第一次调用的时候,指的是 用户 离开这个fragment(并不是被销毁)
通常用于用户的提交(可能用户离开后不会回来了)
8.onStop()
和activity一致, fragment不可见的, 可能情况:activity被stopped了或者 fragment被移除但被,加入到回退栈中,一个stopped的fragment仍然是活着的如果长时间不用也会被移除。
9. onDestroyView()
Fragment中的布局被移除时调用。表示fragemnt销毁相关联的UI布局, 清除所有跟视图相关的资源。
然后这个知识移除视图 并没有销毁而且还没有脱离activity
10.onDestroy()
销毁fragment对象, 跟activity类似了。
11.onDetach()
Fragment和Activity解除关联的时候调用。 脱离activity。
生命周期总结
基本很明了,和Activity有很多相似的地方。我对一些特殊的点进行说明:
onAttach()
和onCreate()
只在 Fragment 与 Activity 第一次关联时调用。onDestroy()
和onDetach()
只在 Fragment 的宿主 Activity 销毁时才会被调用。- 将 Fragment 通过 addToBackStack() 只涉及 onCreateView() 和 onDestroyView() 这之间的生命周期。add() 和 replace() 不会对 Fragment 的生命周期产生影响,但 add() 方法会造成 Fragment 叠加显示。
- Fragment 与 ViewPager 结合使用时的生命周期与第 4 点相似。
- 通过
hide()
、show()
来隐藏、显示Fragment,此时 Fragment 只改变了可见性,并不涉及生命周期的改变。 - 不要在 Fragment 的 onCreate() 方法中操作宿主Activity 的 UI。因为你无法保证此时 宿主Activity 的 UI 已经完全初始化。(某些情况下是可以确保宿主Activity 已经初始化完成的)
Fragment的通信
先说方式:Activity->Fragment通过Bundle,Fragment->Activity通过接口回调方法。
然后详细说明:
Activity->Fragment
Activity要对Fragment发消息可以使用Bundle的方式。写个示例代码,首先在MainActivity中对消息使用Bundle进行封装,然后通过setArguments方法传递进Fragment:
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private MyFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new MyFragment();
String s1 = "这是个测试消息!";
Bundle bundle = new Bundle();
bundle.putString("message",s1);
fragment.setArguments(bundle);
fragmentManager = getSupportFragmentManager();
//点击按钮更新Fragment
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.holder,fragment);
fragmentTransaction.commit();
}
});
}
}
然后在Fragment中将消息使用getArguments拿出来就好了:
public class MyFragment extends Fragment {
private TextView textView;
private Button button;
private String message;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment,null);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//接收消息
Bundle bundle = this.getArguments();
message = bundle.getString("message");
textView = getActivity().findViewById(R.id.textview);
button = getActivity().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText(message);
}
});
}
}
Fragment->Activity
采用接口回调方式来传递消息。
接口回调:把实现了某一接口的类所创建的对象的引用赋给该接口声明的变量,通过该接口变量调用该实现类对象的实现的接口方法。
新建一个接口:
public interface ICallBack {
void getMessageForFragment(String string);
}
然后在Fragment中设置接口的回调方法
public class MyFragment extends Fragment {
private Button button;
private String message;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment,null);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message = "消息:我来自Fragment";
}
});
}
//设置接口回调方法
public void sendMessage(ICallBack callBack){
callBack.getMessageForFragment(message);
}
}
最后在Activity中通过接口的回调方法收到Fragment中发送的消息:
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private MyFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new MyFragment();
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.holder, fragment);
fragmentTransaction.commit();
//点击接收消息按钮接收消息更新UI
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 通过接口回调将消息从fragment发送到Activity
fragment.sendMessage(new ICallBack() {
@Override
public void getMessageForFragment(String string) {
TextView textView = findViewById(R.id.activityText);
if (string != null) {
textView.setText(string);
} else {
Toast.makeText(MainActivity.this, "没有消息", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}