在我的应用程序中,我有简单的接口类:
public interface IOnFinishProgressBarLoading {
public void onFinish(boolean status);
}
并使用某些Fragment
进入活动I我尝试使用Activity
内的已实现接口。例如:
public class ActivityBootstrap extends FragmentActivity implements IOnFinishProgressBarLoading{
...
@Override
public void onFinish(boolean status) {
if (!status) {
pb_retreive_data.setVisibility(View.GONE);
} else {
pb_retreive_data.setVisibility(View.VISIBLE);
}
}
}
现在我的问题是使用Activity
实现的接口,例如
public class FragmentMessagesList extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
IOnFinishProgressBarLoading.onFinish(true);
...
}
}
我得到null异常错误,谢谢
答案 0 :(得分:1)
您可以通过调用getActivity()
的片段来获取您的活动。
现在,您可以将此活动投射到ActivityBootstrap
或IOnFinishProgressBarLoading
并调用onFinish()
方法。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
((IOnFinishProgressBarLoading)getActivity()).onFinish(true);
...
}
答案 1 :(得分:0)
像这样覆盖onAttach方法:
IOnFinishProgressBarLoading callback;
public void onAttach(Activity activity) {
try {
callback = (IOnFinishProgressBarLoading) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Parent Activity must implement IOnFinishProgressBarLoading");
}
super.onAttach(activity);
}