标签: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(); } }
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); } }
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); } }
标签:android style blog http io color ar os java
原文地址:http://blog.csdn.net/coderinchina/article/details/40738709