Fragment横竖屏

第一步,创建两个Fragment。
Fragment1是横屏时的Fragment
Fragment2是竖屏时的fragment。
代码如下:

public class fragment1 extends Fragment{
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View fragment1view = inflater.inflate(R.layout.fragment1,null);
        return fragment1view;
    }
}
public class fragment2 extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View fragment2view=inflater.inflate(R.layout.fragment2,null);
        return fragment2view;
    }
}

然后添加两个布局文件:
fragment1和fragment2
代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#CCC">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#6C3"
        android:text="tomorrow is nice!"/>

</LinearLayout>

最后开始写mainactivity中的代码,具体流程如下:
先要获取窗口的管理器怎样获取呢:通过

WindowManager systemService = (WindowManager) getSystemService(WALLPAPER_SERVICE);
//通过WindowManager对象拿到手机宽高的参数
int height=getWindowManager().getDefaultDisplay().getHeight();
int  width=getWindowManager().getDefaultDisplay().getWidth();

//下面的逻辑就是Fragment动态替换的步骤。
/**

  • 1.0拿到Fragment的管理对象
  • 2.0开启一个事务
    *3.0提交(最下面)
    */
FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction beginTransaction=fragmentManager.beginTransaction();
//当我们手机的高大于宽时,做不同逻辑处理。
    if(height>width){
        //当手机竖屏,加载Fragment1
        beginTransaction.replace(android.R.id.content,new fragment1());
    }else {
        beginTransaction.replace(android.R.id.content,new fragment2());
    }
    //提交
    beginTransaction.commit();
}
    原文作者:仇诺伊
    原文地址: https://www.jianshu.com/p/05e2051264a2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞