码迷,mamicode.com
首页 > 移动开发 > 详细

android 动态创建Fragment

时间:2014-11-03 13:07:07      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   io   color   ar   os   java   

前一遍文章我们讲了静态创建Fragment,这个在实际的开发中几乎不用,都是动态创建的,所谓动态创建就是根据某个条件动态创建Fragment,

现在创建一个android项目 dynamicFragment

MainActivity.java

package com.example.dynamicfragment;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.WindowManager;

public class MainActivity extends Activity {

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

		WindowManager wm = getWindowManager();

		int width = wm.getDefaultDisplay().getWidth();
		int height = wm.getDefaultDisplay().getHeight();
		// 1.获取fragment的管理器
		FragmentManager fm = getFragmentManager();
		// 2.管理里面的fragment 开启事务 保证界面更新 同时成功 或者 同时失败
		FragmentTransaction ft = fm.beginTransaction();
		if (height > width) {
			// 竖屏
			// android.R.id.content 代表的是当前的应用的activity
			ft.replace(android.R.id.content, new Fragment1());

		} else {
			// 横屏
			// android.R.id.content 代表的是当前的应用的activity
			ft.replace(android.R.id.content, new Fragment2());
		}
		ft.commit();
	}
}

Fragment1.java

package com.example.dynamicfragment;


import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		return inflater.inflate(R.layout.fragment1, null);
	}
}

Fragment2.java

package com.example.dynamicfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		return inflater.inflate(R.layout.fragment2, null);
	}
}

xml文件就不贴上了,里面就是一个TextView,所以没啥可说的,当屏幕横屏的时候显示Fragment1,屏幕竖屏的时候显示Fragment2

bubuko.com,布布扣

bubuko.com,布布扣

android 动态创建Fragment

标签:android   style   blog   http   io   color   ar   os   java   

原文地址:http://blog.csdn.net/coderinchina/article/details/40738709

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!