保存多个碎片状态

时间:2015-09-30 12:11:38

标签: android android-fragments

我实现了用于片段事务的AppCompatActivity。只有一个AppCompatActivity,如:

public class UIActivity extends AppCompatActivity {
...
}

片段可以开始另一个事务,导致在后栈中有多个相同类的片段。 (插图)

public class UiFragment extends Fragment implements FileChooserListener {
   mybutton.setOnclickListener(){
   // do some stuff, met some condition and add fragment ( of UiFragment), possibly inflating another view, add previous fragment to back stack
   }
}

这很好用,除非我实现onSaveInstance,在恢复实例上膨胀firstfragment而其他文件丢失。我想从用户停止的地方恢复,并且当用户按下后退按钮时能够访问后堆栈中的片段。

实施

UIActivity中的

UIFragment uif;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
        setContentView(R.layout.activity_ui);


        if (savedInstanceState == null) {


            uif = new UIFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("step", getIntent().getExtras().getSerializable("step"));
            bundle.putString(UIFragment.STEP_KEY, getIntent().getExtras().getString(UIFragment.STEP_KEY));

            uif.setArguments(bundle);


            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.content_frame, uif, "myfragment").commitAllowingStateLoss();
        }
    }


    public void onSaveInstanceState(Bundle outState){
        getSupportFragmentManager().putFragment(outState,"myfragment",uif);
    }
    public void onRestoreInstanceState(Bundle inState){
        uif = (UIFragment)getSupportFragmentManager().findFragmentByTag("myfragment");

    }

将UIFragment添加到堆栈的代码段

public void addNewUIFragment(){
UIFragment uif= new UIFragment ();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("step", step);
                    bundle.putString(UIFragment.STEP_KEY, sData);
                    uif.setArguments(bundle);

                    FragmentTransaction transaction = fragmentManager.beginTransaction();
                    transaction.addToBackStack(null);
                    transaction.setCustomAnimations(R.anim.slide_in, R.anim.slide_out, R.anim.back_slide_in,
                            R.anim.back_slide_out);
                    transaction.add(R.id.content_frame, uif, "myfragment").commitAllowingStateLoss();
}

0 个答案:

没有答案