首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Fragment横竖屏

Fragment横竖屏

作者头像
仇诺伊
发布2018-09-12 14:27:01
8740
发布2018-09-12 14:27:01
举报
文章被收录于专栏:佳爷的后花媛佳爷的后花媛

第一步,创建两个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();
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.02.09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档