2016-08-16 76 views
0

我的活动包含通过XML嵌入的片段A,其包含也通过XML嵌入的片段B.从通过XML加载的片段中的片段访问活动

当我调用B.getActivity()我没有返回。有没有一种简单的方式从B访问活动?

+0

你想要活动方法访问吗? –

+1

请确保您在onAttach中或之后调用getActivity – Ramit

回答

1

我知道这是一个无法回答的问题,但试图从你的片段控制你的活动是一种不好的做法。

如果您需要引用活动来获取上下文或其他东西,那么您只需在片段中使用getActivity()。如果您通过B.getActivity()引用该类,则它将为空,因为您没有查看类的实例,而是查看类构造。由于在创建片段之前没有附加Activity(即使这种情况发生在XML中),引用ClassName.getActivity()不会给你任何东西。所以只需拨打getActivity()就可以了。

处理碎片和活动之间通信的最佳方式是使用接口和回调来发送特定信息。你不应该从片段控制你的应用,活动应该这样做。你只需要从Fragment发回一小段信息回你的父活动。

例子:在您的片段:

private OnFragmentInteractionListener mListener; 

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

//the way to pass information here. Can use return values if you'd like 
//this is what the activity needs to implement 
public interface OnFragmentInteractionListener { 
    void thingHappened(String theInformation); 
} 

//when that thing happens that you want to communicate you call back to the 
//activity like so: 
public void someAction() { 
    mListener.thingHappened("the information"); 
} 

您的活动,您可以通过覆盖方法实现MyFragmentClass.OnFragmentInteractionListener然后你就可以处理好两者之间传递的信息。

public class MyActivity extends AppCompatActivity implements MyFragment.OnFragmentInteractionListener{ 
// most of the code here... 

    //now implement the listener. 
    @override 
    public void thingHappened(String information){ 
     //what you want the activity to do with the information 
    } 
}