请注意,这是官方的沟通方式,Fragment
根据http://developer.android.com/training/basics/fragments/communicating.htmlActivity
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@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 {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onArticleSelected(position);
}
}
但是,我遇到了执行以下技术的代码。
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
((OnHeadlineSelectedListener)this.getActivity()).onArticleSelected(position);
}
到目前为止我测试过它可以工作,即使在配置更改后,我仍然得到最新的Activity
.
我只是想知道,除了谷歌推荐的方法之外,这种方法背后有什么问题吗?例如,getActivity
甚至可以返回 null 吗?