我遇到了一个奇怪的问题:getActivity() 方法总是在片段内返回 null。我在 onAttach() 和 onCreateView() 完成运行后调用它。
该片段位于包含片段堆栈的 FragmentActivity() 中,我向其中添加片段的方式是:
(这段代码是从 Fragment Activity() 的 onCreate() 调用的)
SmartFragment fragment;
fragment = (SmartFragment) Fragment.instantiate(this,
fragmentClassName, params);
mStackOfFragments.add(fragment);
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.tabcontent, fragment);
trans.addToBackStack(null);
trans.commitAllowingStateLoss();
我希望它足够清楚
编辑1:
对 getActivity() 的调用:
protected OnDoneListener nDoneListener = new OnDoneListener() {
@Override
public void OnDone(final int counter, final String name) {
if (getActivity() != null)
((TabActivity) getActivity()).RunOnUiThread(new Runnable() {
……
正在从不同的类调用此回调。
编辑2:
class MemoryManager()
{
private OnDoneListener nDoneListener;
public void setOnDoneListener(OnDoneListener onDoneListener)
{
this.onDoneListner = onDoneListener;
}
public void updateUiOnRequestFinish()
{
onDoneListener.onDone();
}
}
MemoryManaget 本身从不同的回调调用 updateUiOnRequestFinish()
编辑3:
FragmentManager 日志是:
04-08 18:44:05.950: V/FragmentManager(16280): Commit: BackStackEntry{41f9bd60}
`04-08 18:44:05.950: D/FragmentManager(16280): mName=null mIndex=-1 mCommitted=false
04-08 18:44:05.950: D/FragmentManager(16280): Operations:
04-08 18:44:05.950: D/FragmentManager(16280): Op #0: ADD FragmentMyProfile{41f9bc20 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): Setting back stack index 0 to BackStackEntry{41f9bd60}
04-08 18:44:05.950: V/FragmentManager(16280): Run: BackStackEntry{41f9bd60 #0}
04-08 18:44:05.950: V/FragmentManager(16280): Bump nesting in BackStackEntry{41f9bd60 #0} by 1
04-08 18:44:05.950: V/FragmentManager(16280): Bump nesting of FragmentMyProfile{41f9bc20 id=0x7f070126} to 1
04-08 18:44:05.950: V/FragmentManager(16280): add: FragmentMyProfile{41f9bc20 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): Allocated fragment index FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): moveto CREATED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): moveto ACTIVITY_CREATED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:05.990: V/FragmentManager(16280): moveto STARTED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:06.030: V/FragmentManager(16280): moveto RESUMED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
`
对我来说它看起来不错。所以我猜测这个错误与我从回调中调用 getActivity() 的方式有关。