Android架构组件:屏幕旋转后,片段被调用两次

时间:2018-01-19 08:06:31

标签: android android-fragments oncreate screen-rotation model-view

我尝试了解Android ViewModel并且我面临一个奇怪的行为:

启动应用程序时一切正常,但每次轮换时,片段(onCreateView ...,onCreate ...)都会被调用两次。

我使用ModelView在主要活动中实例化片段:

public class MainActivity extends AppCompatActivity {
    String TAG="main";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "onCreate: mainactivity");
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyModelView viewModel =  ViewModelProviders.of(this).get(MyModelView.class);

        viewModel.getmCurrentStep().observe(this,(MyStepModel step) -> {

            if (step != null) {
                Log.i(TAG, "onCreate: step "+step.getmFragment());

            getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.fragmentLayout, step.createFragment())
                            .commit();
            }
        });
    }
}    

碎片:

public class FragmentPrincipal extends Fragment {
    String TAG="main";
    public FragmentPrincipal() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView:fragment1 ");
       return inflater.inflate(R.layout.fragment_principal, container, false);
    }
}

ViewModel:我没有特别关注网上的教程(感谢所有写过他们的人!!!)

public class MyModelView extends ViewModel {                   
    private MutableLiveData<MyStepModel> mCurrentStep=new MutableLiveData<>();

    public MyModelView() {
        mCurrentStep.setValue(MyStepModel.FRAGMENT1);
    }

    public MutableLiveData<MyStepModel> getmCurrentStep() {
        return mCurrentStep;
    }

    //public void toFragment1(){
    //  mCurrentStep.setValue(MyStepModel.FRAGMENT1);
    //}
}

public enum  MyStepModel {
    FRAGMENT1(FragmentPrincipal.class),
    FRAGMENT2(FragmentSecond.class);

    public Class<? extends Fragment> getmFragment() {
        return mFragment;
    }

    private final Class<? extends Fragment> mFragment;

    MyStepModel(Class<? extends Fragment> fragmentClass) {
        mFragment =fragmentClass;
    }

    public  Fragment createFragment(){
       String TAG ="main";
       Log.i(TAG, "createFragment:mystepmodel ");
       try {
           return mFragment.newInstance();
       } catch (InstantiationException | IllegalAccessException e) {
           throw new RuntimeException(e);
       }
   }
}

我愿意接受任何建议。我错过了什么吗?什么?

0 个答案:

没有答案