- FragmentContainerView extends FrameLayout
- FragmentContainerView是专门为Fragments设计的自定义布局。它扩展了FrameLayout,因此它可以可靠地处理Fragment 事务,并且它还具有与Fragment 行为协调的附加特性
- FragmentContainerView应用作Fragments的容器,通常设置在活动的xml布局
- FragmentContainerView将只允许Fragment的Fragment.onCreateView返回的视图。尝试添加任何其他视图将导致IllegalStateException
- 对于17以上的API,FragmentContainerView禁用布局动画和转换。否则,应通过FragmentTransaction.setCustomAnimations完成动画。如果animateLayoutChanges设置为true或直接调用setLayoutTransition,则将引发UnsupportedOperationException
- 使用退出动画的Fragment 在FragmentContainerView的所有其他Fragment 之前绘制。这样可以确保退出的Fragment 不会出现在视图的顶部。
public class MainActivity extends AppCompatActivity { private Button btn_First, btn_Second; private FragmentTransaction fragmentTransaction; private FirstFragment firstFragment = null; private SecondFragment secondFragment = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); initClick(); initFragment(); } private void initView() { btn_First = findViewById(R.id.btn_First); btn_Second = findViewById(R.id.btn_Second); } private void initData() { } private void initClick() { btn_First.setOnClickListener(v -> { showFragment(firstFragment); }); btn_Second.setOnClickListener(v -> { showFragment(secondFragment); }); } private void initFragment() { fragmentTransaction = getSupportFragmentManager().beginTransaction(); firstFragment = new FirstFragment(); fragmentTransaction.add(R.id.fcv, firstFragment); secondFragment = new SecondFragment(); fragmentTransaction.add(R.id.fcv, secondFragment); fragmentTransaction.commit(); showFragment(firstFragment); } private void hideFragment() { if (null != firstFragment) { fragmentTransaction.hide(firstFragment); } if (null != secondFragment) { fragmentTransaction.hide(secondFragment); } } private void showFragment(Fragment fragment) { if (null != fragment) { fragmentTransaction = getSupportFragmentManager().beginTransaction(); hideFragment(); fragmentTransaction.show(fragment); fragmentTransaction.commit(); } }}
来源地址:https://blog.csdn.net/weixin_43969550/article/details/127880837