差点被坑死,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)。下面是看到的一个比较好的解决方案:


[java]  view plain  copy
  1. /* 
  2. * onAttach(Context) is not called on pre API 23 versions of Android and onAttach(Activity) is deprecated 
  3. * Use onAttachToContext instead 
  4. */  
  5.    @TargetApi(23)  
  6.    @Override  
  7.    public void onAttach(Context context) {  
  8.        super.onAttach(context);  
  9.        onAttachToContext(context);  
  10.    }  
  11.   
  12.    /* 
  13.     * Deprecated on API 23 
  14.     * Use onAttachToContext instead 
  15.     */  
  16.    @SuppressWarnings("deprecation")  
  17.    @Override  
  18.    public void onAttach(Activity activity) {  
  19.        super.onAttach(activity);  
  20.        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {  
  21.            onAttachToContext(activity);  
  22.        }  
  23.    }  
  24.   
  25.    /* 
  26.     * Called when the fragment attaches to the context 
  27.     */  
  28.    protected void onAttachToContext(Context context) {  
  29.       //do something  
  30.    }  


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




参考:

http://stackoverflow.com/questions/32077086/android-onattachcontext-not-called-for-api-23

http://stackoverflow.com/questions/32604552/onattach-not-called-in-fragment

你可能感兴趣的:(Android,开发业务)