2017-03-08 21 views
-1

这onAttach方法崩溃我的Android应用程序,我想知道这个方法的相关性,如果我删除方法会发生什么完全片段onAttach()方法崩溃我的代码

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    if (context instanceof OnFragmentInteractionListener) { 
     mListener = (OnFragmentInteractionListener) context; 
    } else { 
     throw new RuntimeException(context.toString() 
       + " must implement OnFragmentInteractionListener"); 
    } 
} 

我删除它和我代码顺利运行,希望以后不会导致任何问题。

+0

您应该指定给出错误的代码行并共享错误。 –

+2

如果'context'不是'OnFragmentInteractionListener'的实例,则抛出异常。这可能是崩溃的原因。 –

回答

0

这里是问题context instanceof OnFragmentInteractionListener

Fragment comunication Android docs.

@Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 

     // This makes sure that the container activity has implemented 
     // the callback interface. If not, it throws an exception 
     try { 
      mListener = (OnFragmentInteractionListener) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() 
        + " must implement OnHeadlineSelectedListener"); 
     } 
    } 
0

此代码为documentation's way用于与活性的片段的工作,当需要在两者之间的通信。我提到它是文档的方式,因为它不是唯一的方法(您可以使用其他技术,例如发布/订阅引擎,例如EventBus)。

如果片段附加到的活动未实现片段期望附加到的接口,则该代码故意抛出RunTimeException。如果它实现了它 - 活动被保存为该接口类型的指针(在你的情况下 - OnFragmentInteractionListener)。

你可以看到行抛出异常:

throw new RuntimeException(context.toString() 
      + " must implement OnFragmentInteractionListener"); 

所以如果你有在控制台“必须实现OnFragmentInteractionListener” - 你知道的片段连接到应该实行OnFragmentInteractionListener但不活动。