context.getActivity()在片段恢复后在片段中返回null

时间:2013-12-06 11:38:51

标签: java android eclipse android-fragments onresume

当片段运行时,context.getActivity()不是null,但当它转向onPause()方法并恢复时,context.getActivity()方法返回null

@Override public View onCreateView(LayoutInflater inflater, 
                                   ViewGroup container, 
                                   Bundle savedInstanceState) {
  view = inflater.inflate(R.layout.levelmission, container, false); 
  initComponents(view); 
  return view; 
}

1 个答案:

答案 0 :(得分:0)

如果您使用

setRetainInstance(true);

每次重新创建视图时都应重置活动,例如:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

 view = inflater.inflate(R.layout.levelmission, container, false); 
 initComponents(view); 
 mActivity = getActivity();

 return view; 
}

然后使用mActivity而不是context.getActivity();