Android – is it safe to convert using getactivity()?
•
Android
I am writing an application with a parent activity and several child fragments. I try to make the fragment communicate with the parent activity. I know there are several ways to do this, including creating an interface and implementing it in the parent activity. However, I am very interested in this method:
ParentActivity activity = (ParentActivity) getActivity();
activity.someMethod();
This method takes less code and less complexity. However, is it safe to do so in production code? Or is the interface more secure?
resolvent:
You can use this –
private ParentActivity callback;
@Override
public void onAttach(Activity activity)
{
//callback = (ParentActivity ) activity;
// make sure there is no cast exception
callback = (ParentActivty.class.isAssignableFrom(activity
.getClass())) ? (ParentActivity) activity : null;
super.onAttach(activity);
}
@Override
public void onDetach()
{
callback = null;
super.onDetach();
}
Now when you make any method call, call it like this –
if(callback!=null)
{
callback.someMethod();
}
This method is very safe
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码