片段中未调用 onAttach() [英] onAttach() not called in Fragment

查看:71
本文介绍了片段中未调用 onAttach()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Fragment 从 AppCompatActivity 启动时不会调用 onAttach(context) 方法.

My Fragment doesn't call onAttach(context) method when it launched from AppCompatActivity.

在 XML 中创建片段:

Fragment creating in XML:

<fragment
    android:id="@+id/toolbar"
    class="package.MainToolbarFragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout="@layout/fragment_main_toolbar" />

但是如果我从 support.v4.Fragment 扩展它,onAttach(context) 调用!

But if I extends it from support.v4.Fragment, onAttach(context) call !

可能是什么问题?

当然,我可以从 v4.Fragment 扩展所有片段,但我不想要它.这是不好的做法吗?还项目 min sdk 14.

Of course, I can extend all fragments from v4.Fragment, but I don't want it. Is it bad practice? Also project min sdk 14.

推荐答案

它没有被调用,因为此方法已添加到 API 23 中.如果您在具有 API 23 (marshmallow) 的设备上运行您的应用程序,则 onAttach(Context) 将被调用.在所有以前的 Android 版本上,onAttach(Activity) 将被调用.

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 Android Versions onAttach(Activity) will be called.

http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)

支持库片段是平台无关的.因此它适用于所有 API 版本.

Support libraries fragment is platform independent. Hence it works on all API versions.

这篇关于片段中未调用 onAttach()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆