Fragment 常见问题

Fragment的onAttach()方法不被调用问题

在Fragment与宿主Activity通过接口传递数据的时候,需要一个接口。

  • 让这个接口作为Fragment的内部成员
  • 让宿主Activity实现这个接口
    但是在Fragment中:
    如果继承的是:android.app.Fragment
    而不是: android.support.v4.app.Fragment;
    那么在onAttach()方法中传递的参数如果为Context而不是Activity,那么Fragment在初始化的时候就不会走onAttach()方法,而接口又是在onAttach()方法里面实例化的,所以执行代码以后一直会报这个自定义的接口空指针。
@Override
    public void onAttach(Context context) {//onAttach方法有两个重载,一个传递的参数是Activity,一个是Context,传递参数为context的在一些Android版本上面由bug,(如果是使用的Fragment包,而不是v4.support.fragment包就会有);
        super.onAttach(context);
        //This makes sure that the container activity has implemented the callback interface. If not, it throws an exception

        //加入判断:
        if (context instanceof MyListener) {//如果该Fragment Attach的Activity实现了MyListener接口
            mylistener = (MyListener) context;//实例化该接口
        }
        //或者捕获异常
//        try {
//            mylistener = (MyListener) context;
//        } catch (ClassCastException e) {
//            throw new ClassCastException(context.toString() + "包含该Fragment的Activity必须实现MyListener接口");
//        }
    }

    /**
     *
     * 如果使用的是 android.app.Fragment;而不是android.support.v4.app.Fragment;
     * 则需要传递参数为Activity
     * @Override
     * public void onAttach(Activity activity) {
     *    super.onAttach(activity);
     *    if (activity instanceof MyListener) {
     *       mylistener = (MyListener) activity;
     *    }
     * }
     */

Fragment中的hide()和show()方法在调用的时候不会走Fragment的生命周期,所以需要手动在hide或者show以后进行uservisible的设置,hide以后seruservisible为false,show以后设置为true

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容