Android的 - onAttach(上下文)不要求API 23
我已经更新了SDK来为片段的最新版本(API 23)和 onAttach(活动)
方法pcated德$ P $。因此,而不是使用该方法,现在,我使用 onAttach(上下文)
但是这一个生命周期中不叫。该活动是 AppCompatActivity
从V7一个实例,该片段是片段类的一个实例( android.app.Fragment
)。
I've updated the SDK to the latest version (API 23) and the onAttach(Activity)
method for fragment is deprecated. So instead of using that method, now I'm using onAttach(Context)
but this one is not called during the lifecycle. The activity is an instance of AppCompatActivity
from v7 and the fragment is an instance of class Fragment (android.app.Fragment
).
任何想法如何获得 onAttach
在API 23的工作?
Any ideas how to get the onAttach
working in API 23?
解决方案
我发现一些答案,可以帮助您了解和解决此问题:
I found some answers that can help you to understand and fix this problem:
解决方案:
-
使用getSupportFragmentManager()会强迫你使用一个片段的支持库。因此,第一个解决方案是与支持LIB()的片段,用getSupportFragmentManager更换所有的碎片。
Using getSupportFragmentManager() will force you to use a Fragment from the support lib. So the first solution is to replace all fragments with the fragment from support lib and using getSupportFragmentManager().
,我已经实现了解决办法是处理2的可能性的(1.应用程序与API℃的设备上运行; 23,应用程序与API的设备上运行> = 23)。
Solution that I've already implemented is to handle 2 possibilities (1. the app is running on a device with API < 23, the app is running on a device with API >= 23).
不久,我在实现我从这次项目中的所有片段的基类和我说这code有:
Shortly, in my implementation I have a base class for all fragments from the project and I added this code there:
/*
* 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) {
}
现在我只是覆盖在哪里,我需要这一切碎片onAttachToContext(上下文)方法。
Now I simply override the onAttachToContext(Context) method on all fragments where I need this.
您应该尝试使用片段的支持库版本。
You should try using the Support library version of Fragment.
您需要切换到进口android.support.v4.app.Fragment;
而不是进口android.app.Fragment;
。你还需要确保你使用 getSupportFragmentManager()
而不是 getFragmentManager()
。
You need to switch to import android.support.v4.app.Fragment;
instead of import android.app.Fragment;
. You'll also need to make sure you're using getSupportFragmentManager()
instead of getFragmentManager()
.