我有我遇到一个奇怪的问题:getActivity()方法总是内部片段返回null。 我叫它onAttach()和onCreateView后()是自己整理的运行。
该片段住包含片段的堆的FragmentActivity()的内部,并且我添加片段给它的方法是:
(此代码被从片段活性的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()的方式。