Android学习笔记(十四)——在执行时加入碎片(附源代码)

在执行时加入碎片


点击获取源代码

将UI切割为多个可配置的部分是碎片的优势之中的一个,但其真正强大之处在于可在执行时动态地把它们加入到活动中。


1、使用上一篇创建的Fragments项目,在main.xml文件里凝视掉两个<fragment>元素;

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:



转载于:https://www.cnblogs.com/lcchuguo/p/5183640.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值