Android中关于Fragment的那些事、那些坑

TaylorFahey 8年前
   <h2>引言</h2>    <p>在Android3.0开始,Android引入了Fragment。当初最主要的目的是为了给大屏幕手持设备提供更加灵活和动态的UI设计。随着应用功能越来越多,界面越来越复杂,我们会利用Fragment对Activity的界面进行模块化编程。比如一个Activity界面内有多个请求,每个请求得到的结果展示不同的UI片段,那么我们就可以将Activity利用Fragment来完成UI模块化。目前在我目前的项目中,Fragment的地位已经举足轻重了。当然我写篇文章,并不是简单的介绍Fragment的用法,而是结合我在项目中使用Fragment所遇到的问题进行说明。</p>    <h2>Fragment的生命周期</h2>    <p>Fragment与Activity一样也是具有生命周期的,它的生命周期与Activity息息相关。下面看下Fragment生命周期流程图(摘自Android官方开发文档)</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/91b2bb0dc9207898818291854066dca2.png" alt="Android中关于Fragment的那些事、那些坑" width="317" height="847"></p>    <p style="text-align: center;"> </p>    <p><br> 大体上Fragment的生命周期与Activity类似,但是也有自己独有的生命周期方法。每个生命周期的意义大家可以看看<a href="/misc/goto?guid=4959673157382697946">Android Fragment</a>,这里就不做详解了。</p>    <h2>Fragment与Activity之间生命周期的关系</h2>    <p>每个Fragment实例存在于单独的一个Activity实例中,因此Fragment必须以某种方式与Activity的生命周期合作。Fragment不仅与Activity的生命周期合作,而且他们之间有“密切”联系。</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/8c5c1e82df783d5eb3b874385a79959c.png" alt="Android中关于Fragment的那些事、那些坑" width="397" height="340"></p>    <p style="text-align: center;">Fragment lifecycle, from added to active</p>    <p><br> 上图是Fragment创建到激活过程与Activity相关的生命周期图,为了验证该过程,我们写一个demo程序来进行验证。<br> 打印Activity生命周期方法相关方法代码:</p>    <pre>  <code class="language-java">public class MainActivity extends FragmentActivity {      private static final String TAG = "KissonChan";        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          Log.d(TAG, "Activity onCreate");          setContentView(R.layout.activity_main);          TestFragment fragment = (TestFragment)getFragmentManager().findFragmentById(R.id.test);      }        @Override      public void onAttachFragment(Fragment fragment) {          super.onAttachFragment(fragment);          Log.d(TAG, "Activity onAttachFragment");      }        @Override      protected void onStart() {          super.onStart();          Log.d(TAG, "Activity onStart");      }        @Override      protected void onResume() {          super.onResume();          Log.d(TAG, "Activity onResume");      }        @Override      protected void onPause() {          super.onPause();          Log.d(TAG, "Activity onPause");      }        @Override      protected void onStop() {          super.onStop();          Log.d(TAG, "Activity onStop");      }        @Override      protected void onSaveInstanceState(Bundle outState) {          super.onSaveInstanceState(outState);          Log.d(TAG, "Activity onSaveInstanceState");      }        @Override      protected void onDestroy() {          super.onDestroy();          Log.d(TAG, "Activity onDestroy");      }        @Override      protected void onRestart() {          super.onRestart();          Log.d(TAG, "Activity onRestart");      }  }</code></pre>    <p>打印Fragment生命周期方法相关方法代码:</p>    <pre>  <code class="language-java">public class TestFragment extends Fragment {      private static final String TAG = "KissonChan";      private View mRootView;        @Override      public void onAttach(Activity activity) {          super.onAttach(activity);          Log.e(TAG, "Fragment onAttach");      }        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          Log.e(TAG, "Fragment onCreate");      }        @Nullable      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,          Bundle savedInstanceState) {          Log.e(TAG, "Fragment onCreateView");          mRootView = inflater.inflate(R.layout.fragment_test, container, false);          return mRootView;      }        @Override      public void onActivityCreated(Bundle savedInstanceState) {          super.onActivityCreated(savedInstanceState);          Log.e(TAG, "Fragment onActivityCreated");      }        @Override      public void onStart() {          super.onStart();          Log.e(TAG, "Fragment onStart");      }        @Override      public void onResume() {          super.onResume();          Log.e(TAG, "Fragment onResume");      }        @Override      public void onPause() {          super.onPause();          Log.e(TAG, "Fragment onPause");      }        @Override      public void onStop() {          super.onStop();          Log.e(TAG, "Fragment onStop");      }        @Override      public void onSaveInstanceState(Bundle outState) {          super.onSaveInstanceState(outState);          Log.e(TAG, "Fragment onSaveInstanceState");      }        @Override      public void onDestroyView() {          super.onDestroyView();          Log.e(TAG, "Fragment onDestroyView");      }        @Override      public void onDetach() {          super.onDetach();          Log.e(TAG, "Fragment onDetach");      }        @Override      public void onDestroy() {          super.onDestroy();          Log.e(TAG, "Fragment onDestroy");      }  }</code></pre>    <p>程序的执行结果是:</p>    <pre>  <code class="language-java">05-12 11:38:42.901 32590-32590/? D/KissonChan: Activity onCreate  05-12 11:38:42.911 32590-32590/? E/KissonChan: Fragment onAttach  05-12 11:38:42.911 32590-32590/? D/KissonChan: Activity onAttachFragment  05-12 11:38:42.911 32590-32590/? E/KissonChan: Fragment onCreate  05-12 11:38:42.911 32590-32590/? E/KissonChan: Fragment onCreateView  05-12 11:38:42.911 32590-32590/? E/KissonChan: Fragment onActivityCreated  05-12 11:38:42.911 32590-32590/? D/KissonChan: Activity onStart  05-12 11:38:42.911 32590-32590/? E/KissonChan: Fragment onStart  05-12 11:38:42.911 32590-32590/? D/KissonChan: Activity onResume  05-12 11:38:42.911 32590-32590/? E/KissonChan: Fragment onResume</code></pre>    <p>在Fragment从激活态到销毁也有类似的生命周期过程,不过与创建过程是相反。当Fragment的生命周期方法调用之后才调用对应的Activity生命周期方法,如下图。</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/e678e82249ec155e04940d85713bd7da.png" alt="Android中关于Fragment的那些事、那些坑" width="510" height="331"></p>    <p style="text-align: center;">Fragment lifecycle, from active to destroy</p>    <blockquote>     <p>注意:如果正常结束Activity,onSaveInstanceState方法将不被调用。如果用户按下home键或者电源键等相关操作,将Activity置于后台,那么onSaveInstanceState将被调用。</p>    </blockquote>    <p>正常结束Activity程序运行结果是:</p>    <pre>  <code class="language-java">05-12 14:10:44.131 8266-8266/? E/KissonChan: Fragment onPause  05-12 14:10:44.131 8266-8266/? D/KissonChan: Activity onPause  05-12 14:10:44.381 8266-8266/? E/KissonChan: Fragment onStop  05-12 14:10:44.381 8266-8266/? D/KissonChan: Activity onStop  05-12 14:10:44.381 8266-8266/? E/KissonChan: Fragment onDestroyView  05-12 14:10:44.381 8266-8266/? E/KissonChan: Fragment onDestroy  05-12 14:10:44.381 8266-8266/? E/KissonChan: Fragment onDetach  05-12 14:10:44.381 8266-8266/? D/KissonChan: Activity onDestroy</code></pre>    <p>按下home键程序运行结果是:</p>    <pre>  <code class="language-java">05-12 14:12:01.781 8266-8266/? E/KissonChan: Fragment onPause  05-12 14:12:01.781 8266-8266/? D/KissonChan: Activity onPause  05-12 14:12:02.041 8266-8266/? E/KissonChan: Fragment onSaveInstanceState  05-12 14:12:02.041 8266-8266/? D/KissonChan: Activity onSaveInstanceState  05-12 14:12:02.041 8266-8266/? E/KissonChan: Fragment onStop  05-12 14:12:02.041 8266-8266/? D/KissonChan: Activity onStop</code></pre>    <p>如果对Fragment和Activity的生命周期有深入了解想法的小伙伴,可以自己阅读相关源码。我这里仅仅是抛砖引玉,做个简单介绍,为后续介绍工作过程中碰到的问题做一个铺垫。</p>    <h2>Fragment的两种声明方式</h2>    <p>Android提供了两种声明Fragment的方式,这两种方式上使用会有不同。同时也有一些需要注意的地方。</p>    <h2>在Activity布局中添加Fragment</h2>    <p>这种方式数据比较常用,在Activity布局中声明fragment。</p>    <pre>  <code class="language-xml">    <fragment          android:id="@+id/test"          android:name="com.dighammer.kisson.testfragment.TestFragment"          android:layout_width="match_parent"          android:layout_height="wrap_content"/></code></pre>    <p>随后,在Activity通过如下方法初始化Fragment。</p>    <pre>  <code class="language-java">TestFragment fragment = (TestFragment)getFragmentManager().findFragmentById(R.id.test);</code></pre>    <h2>在代码中将Fragment添加到已有ViewGroup中</h2>    <p>这种方式我自己用的比较多,方法如下:</p>    <pre>  <code class="language-java">FragmentTransaction transaction = getFragmentManager().beginTransaction();  TestFragment fragment = new TestFragment();  transaction.add(R.id.container,fragment);  //transaction.replace(R.id.container,fragment);  transaction.commit();</code></pre>    <p>这里咱们需要注意FragmentTransaction中add和replace方法的区别。</p>    <ol>     <li>add方法是把Fragment添加到ViewGroup中,通过该方法可以添加多个Fragment。</li>     <li>replace方法会把ViewGroup中的原有Fragment先remove掉然后再add新Fragment。</li>    </ol>    <p>使用add方法可以避免再次创建Fragment实例,一般情况是建议使用add方法,并配合FragmentTransaction的show和hide方法来使用。</p>    <h2>那些年,我踩过的Fragment的坑</h2>    <h3>第一个坑</h3>    <pre>  <code> java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState   at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1331)  at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1349)  at android.app.BackStackRecord.commitInternal(BackStackRecord.java:735)  at android.app.BackStackRecord.commit(BackStackRecord.java:711)  at com.dighammer.kisson.testfragment.MainActivity$1.run(MainActivity.java:30)  at android.os.Handler.handleCallback(Handler.java:739)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5273)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)</code></pre>    <p>该类型的Crash开始的时候在我们的后台崩溃日志出现很多次。<br> 这里我写了一段代码,运行后可以百分比复现。</p>    <pre>  <code class="language-java">public class MainActivity extends FragmentActivity {        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          new Handler().postDelayed(new Runnable() {              @Override              public void run() {                  FragmentTransaction transaction = getFragmentManager().beginTransaction();                  TestFragment fragment = new TestFragment();                  transaction.add(R.id.container, fragment);                  transaction.commit();              }          }, 5000);      }</code></pre>    <p>当程序界面显示出来后,按home键,过接近5秒后,就会出现该奔溃日志。<br> 原因是FragmentTransaction中的commit方法必须在onSaveInstanceState之前调用。<br> 那么如何解决了?在FragmentTransaction中提供了commitAllowingStateLoss方法,通过调用该方法就不用关心Activity的状态是否保存。</p>    <h3>第二个坑</h3>    <p>情景再现,先看代码。</p>    <pre>  <code class="language-java">public class MainActivity extends FragmentActivity {        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          FragmentTransaction transaction = getFragmentManager().beginTransaction();          TestFragment fragment = new TestFragment();          transaction.add(R.id.container, fragment);          transaction.commit();          fragment.setText("kisson chan");        }  }</code></pre>    <p>运行后,会报如下错误。</p>    <pre>  <code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference                                                         at com.dighammer.kisson.testfragment.TestFragment.setText(TestFragment.java:53)                                                         at com.dighammer.kisson.testfragment.MainActivity.onCreate(MainActivity.java:18)                                                         at android.app.Activity.performCreate(Activity.java:6041)                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)                                                          at android.app.ActivityThread.access$800(ActivityThread.java:154)                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)                                                          at android.os.Handler.dispatchMessage(Handler.java:102)                                                          at android.os.Looper.loop(Looper.java:135)                                                          at android.app.ActivityThread.main(ActivityThread.java:5273)                                                          at java.lang.reflect.Method.invoke(Native Method)                                                          at java.lang.reflect.Method.invoke(Method.java:372)                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)</code></pre>    <p>这里是空指针异常,TestFragment中的TextView还未被初始化。但是,如果我们通过Activity布局中声明Fragment则不会报错,代码如下。</p>    <pre>  <code class="language-java">public class MainActivity extends FragmentActivity {        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          TestFragment fragment = (TestFragment)getFragmentManager().findFragmentById(R.id.test);          fragment.setText("kisson");      }  }</code></pre>    <p>原因其实很简单,通过Activity布局中声明Fragment,Fragment的初始化以及其布局中控件的初始化都发生在Activity的setContentView方法中。所以在setContentView方法调用之后,我们可以直接操作Fragment中的控件。<br> 但是通过代码将Fragment添加到ViewGroup的方式,并不能在Activity的onCreate方法中去操作Fragment中的控件,只能等到onCreate完成之后调用。<br> 如果必须要在Activity的onCreate方法中操作Fragment中的控件,这里我提供一个参考办法。</p>    <pre>  <code class="language-java">public class TestFragment extends Fragment{        private View mRootView;        private TextView mTextView;        private String mTextStr;        @Nullable      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          mRootView = inflater.inflate(R.layout.fragment_test,container,false);          return mRootView;      }        @Override      public void onActivityCreated(Bundle savedInstanceState) {          super.onActivityCreated(savedInstanceState);          mTextView = (TextView)mRootView.findViewById(R.id.text);          if (!TextUtils.isEmpty(mTextStr)){              mTextView.setText(mTextStr);          }      }      /**       * 如果mTextView为空,即mTextView还未被初始化,那么将text赋值给mTextStr,等到onActivityCreated调用后再setText       * 如果mTextView不为空,则直接调用TextView的setText方法进行赋值       * */      public void setText(String text){          if (mTextView == null){              mTextStr = text;          }          else {              mTextView.setText(text);          }      }  }</code></pre>    <h3>第三个坑</h3>    <p>情景再现,先看代码。</p>    <pre>  <code class="language-java">public class TestFragment extends Fragment{        private View mRootView;        @Nullable      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          mRootView = inflater.inflate(R.layout.fragment_test,container,false);          return mRootView;      }        @Override      public void onActivityCreated(Bundle savedInstanceState) {          super.onActivityCreated(savedInstanceState);          new Handler().postDelayed(new Runnable() {              @Override              public void run() {                  ((MainActivity) (getActivity())).print();              }          },5000);      }  }</code></pre>    <p>继续上代码</p>    <pre>  <code class="language-java">public class MainActivity extends FragmentActivity {        private static final String TAG = "KissonChan";      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          FragmentTransaction transaction = getFragmentManager().beginTransaction();          TestFragment fragment = new TestFragment();          transaction.add(R.id.container,fragment);          transaction.commit();      }        public void print() {          Log.d(TAG, "KissonChan");      }  }</code></pre>    <p>当程序Activity显示出来后,接着按下返回键结束Activity,静待五秒后,出现以下崩溃日志。</p>    <pre>  <code> Process: com.dighammer.kisson.testfragment, PID: 15870  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.dighammer.kisson.testfragment.MainActivity.print()' on a null object reference                                                         at com.dighammer.kisson.testfragment.TestFragment$1.run(TestFragment.java:41)                                                         at android.os.Handler.handleCallback(Handler.java:739)                                                         at android.os.Handler.dispatchMessage(Handler.java:95)                                                         at android.os.Looper.loop(Looper.java:135)                                                         at android.app.ActivityThread.main(ActivityThread.java:5273)                                                         at java.lang.reflect.Method.invoke(Native Method)                                                         at java.lang.reflect.Method.invoke(Method.java:372)                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)</code></pre>    <p>因为MainActivity已经被销毁,五秒钟后在TestFragment实例中会调用MainActivity的print方法,所以抛出空指针异常。<br> 这里很奇怪,Activity已经被销毁了,为什么Fragment还能继续苟活。<br> 这是因为Fragment并不会随着Activity的回收而被系统回收,所有被创建的Fragment都会保存在一个Bundle里面。所以会导致以上崩溃。所以在一些延时操作或者线程操作中调用getActivity最好做下为空判断!</p>    <h2>结尾</h2>    <p>Fragment作为模块化UI编程类,极大方便了我们代码设计。但是同时我们也要深刻理解其生命周期及其意义。有时间大家可以看看源码,发现其中的奥秘!</p>    <p> </p>    <p>文/Kisson(简书)<br> via:http://www.jianshu.com/p/e658ffc02211<br>  </p>