我有一个扩展android.app.Fragment的片段。在某些情况下,在 onCreateView 内部,当我尝试将 Application 强制转换为我的 Application 实现时,我会遇到java.lang.ClassCastException。
public class SketchFragment extends android.app.Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.layout, container, false);
ButterKnife.bind(this,inflate);
MyApplication application = (MyApplication) getActivity().getApplicationContext();
//Previously, I tried to
//MyApplication application = (MyApplication) getActivity().getApplication()
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,只有在Android 6 中,我才在 <5% 的所有用户中出现此错误(我的 Crashlytics 日志说)。我的 Crashlytics 日志如下:
致命异常:java.lang.ClassCastException:android.app.Application 无法转换为 com.example.app.MyApplication
Run Code Online (Sandbox Code Playgroud)at com.example.app.ui.activity.main.MyFragment.onCreateView(MyFragment.java:95) at android.app.Fragment.performCreateView(Fragment.java:2281) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:983) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1163) at android.app.BackStackRecord.run(BackStackRecord.java:793) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1552) at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487) at …