【问题标题】:How can I skip onResume while starting of an Fragment?如何在片段开始时跳过 onResume?
【发布时间】:2017-10-11 16:45:54
【问题描述】:

基本上,我希望在 OnResume() 中放置一些代码,该代码仅在用户从从该片段调用的活动中按回时触发,但 onResume() 中的代码不应在开始时执行

【问题讨论】:

    标签: android android-fragments android-lifecycle


    【解决方案1】:

    您可以使用startActivityForResult 启动活动,当您回来时会调用onActivityResult

    如果您仍然想要onResume 中提到的行为,您可以使用布尔标志:

    boolean started = false;
    
    @Override
    public void onResume() {
        super.onResume();
        if(started) {
            //do your task
        } else {
            started = true;
        }
    }
    

    但是onActivityResult 是这样做的好方法。

    【讨论】:

    • 对于 startActivityForResult ,看来我必须从父活动开始,然后哪个片段得到了回报。我可以从片段中做到吗?
    • @ishandutta2007 你也可以从片段中完成
    【解决方案2】:

    这是一种相当 hack-ish 的技术,但它确实有效。

    首先你在类中声明一个布尔值:

    private boolean isInitialized = false;
    

    onResume 中,检查值。如果为假,则将其设置为真。如果是真的,你执行你想要的代码(代码示例在底部)。

    记住片段生命周期:


    (来源:xamarin.com

    onResume 是片段启动时最后调用的事件。因此,所有这些都必须在 onResume 中调用才能正确使用(如果布尔值在 onCreate 中设置为 true,则在 onResume 中始终为 true,即使在第一次启动时也是如此)

    所以基本上,您的onResume 方法应该如下所示:

    public void onResume(){
        super.onResume();
        if(!isInitialized) isInitialized = true;
        else{
            //Your code here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多