[转]Android fragment onAttach方法的坑

今天在写一个Fragment的Demo中,在onAttach中进行赋值工作,结果显示并没有赋值,意味着onAttach并没有调用,最终在stackFlow找到了答案:

It's not called because this method has been added in API 23. If you run your application on a device with API 23 (marshmallow) then onAttach(Context) will be called. On all previous AndroidVersions onAttach(Activity) will be called.

我是看 **onAttach(Activity) **方法被deprecation了,所以用最新的 onAttach(Context) 方法,哪想到在API低于 23 的版本中不会去调用后者,只会去调用onAttach(Activity)。下面是看到的一个比较好的解决方案:

/* 
* onAttach(Context) is not called on pre API 23 versions of Android and onAttach(Activity) is deprecated 
* Use onAttachToContext instead 
*/  
   @TargetApi(23)  
   @Override  
   public void onAttach(Context context) {  
       super.onAttach(context);  
       onAttachToContext(context);  
   }  
  
   /* 
    * Deprecated on API 23 
    * Use onAttachToContext instead 
    */  
   @SuppressWarnings("deprecation")  
   @Override  
   public void onAttach(Activity activity) {  
       super.onAttach(activity);  
       if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {  
           onAttachToContext(activity);  
       }  
   }  
  
   /* 
    * Called when the fragment attaches to the context 
    */  
   protected void onAttachToContext(Context context) {  
      //do something  
   }  

在用Fragment时,这样复写onAttach方法就可以减少API的影响了。ps:也真是出鬼了,昨天手机才升级的6.0,结果今天搞的手机测试正常,平板(api:4.4)测试不正常,愁死我了。这个问题告诉我,google不断发布兼容库意义重大啊!!!

原文章:
差点被坑死,Fragment onAttach方法没有被调用

你可能感兴趣的:([转]Android fragment onAttach方法的坑)