zoukankan      html  css  js  c++  java
  • android 动态创建Fragment

    前一遍文章我们讲了静态创建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



  • 相关阅读:
    Go实现线程池
    Go语言工程结构
    Go语言示例-函数返回多个值
    Go语言参数中的三个点是干什么的
    go语言示例-Timer计时器的用法
    Go语言的类型转化
    iOS 修改通讯录联系人地址(address)崩溃原因分析
    tableview小结-初学者的问题
    Objective-C总Runtime的那点事儿(一)消息机制
    论坛源码推荐(11.6):iPhone6/6 plus屏幕适配Demo,Java代码转Objective-C
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6842336.html
Copyright © 2011-2022 走看看