效果图如下:


项目结构图如下:


Fragment1:

package com.demo.dongtaifragment;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment2 extends Fragment {    //显示faragemnt1 自己要显示的内容    @Nullable    @Override    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragemnt2, null);        return view;    }}

Fragment2:

package com.demo.dongtaifragment;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment2 extends Fragment {    //显示faragemnt1 自己要显示的内容    @Nullable    @Override    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragemnt2, null);        return view;    }}

MainActivity:

package com.demo.dongtaifragment;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.WindowManager;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //[1]获取手机的分辨率        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);        int width = wm.getDefaultDisplay().getWidth();        int height = wm.getDefaultDisplay().getHeight();        FragmentManager fragmentManager  = getFragmentManager();        //开启事务        FragmentTransaction beginTransaction = fragmentManager.beginTransaction();        Fragment1 fragment1 = new Fragment1();        //判断横竖        if(height>width){            //说明是竖屏  加载一个fragment           beginTransaction.replace(android.R.id.content, new Fragment1());        }else{            //说明是横屏            beginTransaction.replace(android.R.id.content, new Fragment2());        }        //最后一步 记得commit        beginTransaction.commit();    }}

fragemnt1.xml:

<?xml version="1.0" encoding="utf-8"?>    

fragemnt2.xml:

<?xml version="1.0" encoding="utf-8"?>    

加群:522841375 可获取Android高级开发资料哦


更多相关文章

  1. android获取recycleview滚动的距离
  2. Display_获取屏幕宽高
  3. 模拟ProgressBar下载进度显示
  4. Android(安卓)Calendar的学习与运用
  5. Android(安卓)ViewFlipper简单应用
  6. Intent+Bundle 传值
  7. Android--截屏(支持Android7.1.1,无需root)
  8. android入门 spinner
  9. ScreenUtil

随机推荐

  1. 服务主数据的创建和特性的维护
  2. ALV双击弹出新ALV,并响应新ALV事件
  3. 自学第七十九天
  4. C语言 13.0
  5. 选择屏幕动态显示BLOCK title
  6. vue学习之路(认识vue,挂载点,数据注入,响应式
  7. 第3章 0127-常用运算与流程控制,学心得、
  8. k8s 常用命令
  9. 我的第八个代码
  10. 事件与常用函数