片段类字段因未知原因而被取消

时间:2014-03-05 20:17:03

标签: java android oop android-fragments

所以我有一个嵌套的片段,如:

public class AbstractFragment extends Fragment {
    public int resultCode;

    protected void startFragment(AbstractFragment fragment, int resultCode){
        this.resultCode = resultCode;
        Log.w(this, "startFragment(). fragment: "+fragment+" resultCode: "+this.resultCode);
        ((MainActivity)getActivity()).addFragmentToBackStack(fragment);
    }
}

和MainActivity有相应的方法:

public class MainActivity extends FragmentActivity {
    public void addFragmentToBackStack(Fragment fragment){
        Log.w(this, "addFragmentToBackStack(). fragment: "+fragment+" resultCode: "+((AbstractFragment) fragment).resultCode);
        getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.content_frame, fragment, fragment.getClass().getName())
        .addToBackStack(null)
        .commit();
    }
}

和片段正在启动,如

public class DynamicsFragment extends AbstractFragment{
public static final int DYNAMICS_CODE = 2;
...
startFragment(new DynamicsAddFragment(), DYNAMICS_CODE);
...
}

我得到的结果令我感到困惑因为根据日志,OOP的基本原理并不起作用:

03-05 21:35:05.700: W/DynamicsFragment(8533): startFragment(). fragment: DynamicsAddFragment{413453d8} requestCode: 2
03-05 21:35:05.700: W/MainActivity(8533): addFragmentToBackStack(). fragment: DynamicsAddFragment{413453d8} requestCode: 0

我检查了整个项目,期望找到一些代码,我可以将resultCode设置为0,但没有。设置的唯一地点resultCode位于startFragment AbstractFragment方法,DynamicsAddFragment方法AbstractFragment范围resultCode。如果创建DynamicsAddFragment的新实例但项目中没有此类代码,则startFragment也将设置为零。
两个日志输出行都是一个,后跟一个预期执行的行。但ATM {{1}}运行resultCode字段初始化为2,同时当MainActivity方法运行时,该字段已经为空。例如,对于String类型等其他字段也会发生同样的情况。但实例化的片段FOA是一个对象!正如您所看到的,对象的运行时标识(唯一的运行时哈希内存标识{413453d8})是相同的!所以它的确是同一个对象!它不是同一个对象的新/另一个实例!怎么可能?!

1 个答案:

答案 0 :(得分:0)

您在this.resultCode = resultCode;上呼叫this,即在DynamicsFragment上,而稍后您从另一个片段DynamicsAddFragment获取此值,我假设。这应该有效:

protected void startFragment(AbstractFragment fragment, int resultCode){
    fragment.resultCode = resultCode;
    Log.w(this, "startFragment(). fragment: "+fragment+" resultCode: "+fragment.resultCode);
    ((MainActivity)getActivity()).addFragmentToBackStack(fragment);
}