在运行时添加碎片
将UI分割为多个可配置的部分是碎片的优势之一,但其真正强大之处在于可在运行时动态地把它们添加到活动中。
1、使用上一篇创建的Fragments项目,在main.xml文件中注释掉两个元素;
2、在FragmentActivity.java中添加下面的代码:
FragmentManager fragmentManager = getSupportFragmentManager();//向活动添加碎片
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();//添加FragmentTransaction来操作碎片
//获取设备当前的屏幕信息:判断处于纵向模式还是横向模式
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
if (display.getWidth() > display.getHeight()) {
//横向模式
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(android.R.id.content, fragment1);
} else {
//纵向模式
Fragment2 fragment2 = new Fragment2();
fragmentTransaction.replace(android.R.id.content, fragment2);
}
fragmentTransaction.commit();提交更改
3、在模拟器上运行程序,效果如下:
当设备处于纵向模式时,显示碎片2,:
当设备处于横向模式时,显示碎片1: