Android动态添加Fragment
16lz
2021-01-26
效果图如下:
项目结构图如下:
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高级开发资料哦
更多相关文章
- android获取recycleview滚动的距离
- Display_获取屏幕宽高
- 模拟ProgressBar下载进度显示
- Android(安卓)Calendar的学习与运用
- Android(安卓)ViewFlipper简单应用
- Intent+Bundle 传值
- Android--截屏(支持Android7.1.1,无需root)
- android入门 spinner
- ScreenUtil