0
A
回答
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
}
}
你想要活动方法访问吗? –
请确保您在onAttach中或之后调用getActivity – Ramit