2、核心代码 a) FragmentHorizontal.java
package cn.zengfansheng.dynamicfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentHorizontal extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_vertical, null);
}
} b) FragmentVertical.java
package cn.zengfansheng.dynamicfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentVertical extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_horizontal, null);
}
} c) MainActivity.java
package cn.zengfansheng.dynamicfragment;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
public class MainActivity extends Activity {
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 需求:横屏:显示fragmenthorizontal 竖屏:显示fragmentvertical
// 1、获取FragmentManager对象
FragmentManager fragmentManager = this.getFragmentManager();
// 2、开启事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// 3、获取手机的屏幕尺寸
WindowManager windowManager = this.getWindowManager();
Display defaultDisplay = windowManager.getDefaultDisplay();
int windowWidth = defaultDisplay.getWidth();
int windowHeight = defaultDisplay.getHeight();
// 4、判断横竖屏幕
if (windowWidth>windowHeight) {//横屏
//显示fragmenthorizontal
fragmentTransaction.replace(android.R.id.content, new FragmentHorizontal());
}else {//竖屏
//显示fragmentvertical
fragmentTransaction.replace(android.R.id.content, new FragmentVertical(), null);
}
// 5、提交事务
fragmentTransaction.commit();
}
} |