天天看點

android 橫豎屏切換不同布局,Fragment 橫豎屏切換時加載不同的布局

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

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" >

activity_fragment2.xml

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#0000ff"

tools:context=".MainActivity" >

3、在程式中調用

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();

}

}