Android onCreateView在方向更改后重新创建片段后运行两次

Android onCreateView在方向更改后重新创建片段后运行两次,android,android-fragments,Android,Android Fragments,我有一个活动只包含一个框架布局,其中显示一个片段。片段仅包含一个按钮 该应用程序的工作原理是,单击按钮时,按钮的背景颜色会发生变化。片段从MainActivity中定义的数组接收颜色值 活动代码为: public class MainActivity extends AppCompatActivity { frag a; FragmentManager fm; static int color[] = {Color.RED,Color.BLUE,Color.GREEN};

我有一个
活动
只包含一个
框架布局
,其中显示一个
片段
片段
仅包含一个
按钮

该应用程序的工作原理是,单击按钮时,按钮的背景颜色会发生变化。片段从
MainActivity
中定义的数组接收颜色值

活动代码为:

public class MainActivity extends AppCompatActivity {
    frag a;
    FragmentManager fm;
    static int color[] = {Color.RED,Color.BLUE,Color.GREEN};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        a = new frag();
        fm = getFragmentManager();
        FragmentTransaction ft = 
            (fm).beginTransaction().add(R.id.framelayout, a);
        ft.commit();
    }
}
片段代码是:

public class frag extends Fragment implements View.OnClickListener {

    View v;
    Button button;
    int i = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (savedInstanceState!=null) {
            i = (int) savedInstanceState.get("i");
        }

        v = inflater.inflate(R.layout.fragment_frag, container, false);
        button = (Button) v.findViewById(R.id.button);
        button.setBackgroundColor(MainActivity.color[i]);
        button.setOnClickListener(this);
        return v;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("i",i);
    }

    @Override
    public void onClick(View vx) {
        i++;
        if(i%3==0)
            i=0;
        button.setBackgroundColor(MainActivity.color[i]);
    }
}
问题在于,当屏幕旋转并重新创建片段时,
onCreateView
会连续运行两次。第一次,它有一个
非null
savedInstanceState
,但第二次,
savedInstanceState
变成
null
(我使用调试器观察到了这一点)。因此,在重新创建片段时,按钮的颜色总是变为红色,这是
颜色数组
的第一个索引处的颜色,似乎应用程序的
状态
根本没有保存。


为什么会发生这种情况?

当您旋转时,活动中的onCreate
会再次调用,这意味着将创建另一个片段并将其添加到您的
框架布局中。旧的将被重新创建,因此您有两个。检查创建活动中的
savedInstanceState
。如果它不为null,则您的活动已被重新创建,并且该片段可能已经存在。您还可以执行
fragmentManager.findFragmentById(id)
,并在再次添加之前检查它是否在那里。

谢谢,伙计,这很好。我还想知道,当我们声明:fragment a=new fragment()时,是重新创建旧片段,还是片段管理器会记住旧片段并在重新创建活动时立即重新创建它@OnFragmentManager会重新创建它,因为您是第一次添加它的。因此,只需在
setContentView
之后运行一次代码。