1、创建两个FragmentActivity 让它继承 Fragment ,这里最低版本为11
package com.example.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.activity_fragment1, null);
}
}
package com.example.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.activity_fragment2, null);
}
}
2、创建两个.xml 文件,用来显示屏幕切换时所用到的布局
activity_fragment1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/ic_launcher"
tools:context=".MainActivity" >
</RelativeLayout>
activity_fragment2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
tools:context=".MainActivity" >
</RelativeLayout>
package com.example.fragment;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int windowHeight = this.getResources().getDisplayMetrics().heightPixels; //获取当前屏幕的高
int windowWidth = this.getResources().getDisplayMetrics().widthPixels; //获取当前屏幕的宽
Fragment1 f1 = new Fragment1();
Fragment2 f2 = new Fragment2();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if(windowWidth > windowHeight){ //横屏
ft.replace(android.R.id.content, f1); //是横屏的时候显示f1的布局
}else {
ft.replace(android.R.id.content, f2); //显示f2 中的布局
}
ft.commit();
}
}