根据documentation,有两种向活动添加片段的方法:
首先:在活动的布局文件中声明该片段。
第二:以编程方式将片段添加到现有的ViewGroup。
仅当我尝试第二种方法然后更改配置(例如旋转)时,onCreateView
在第一次旋转中被调用两次,在第二次旋转中被调用三次,依此类推。
为什么onCreateView
的这种累积行为仅在以编程方式将片段添加到活动时才会发生?
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExampleFragment exampleFragment = new ExampleFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.fragment_container, exampleFragment)
.commit();
}
}
ExampleFragment.java
public class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("ExampleFragment", "onCreateView");
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
example_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</android.support.constraint.ConstraintLayout>