fragment的切换
1、视图
1)主视图
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="horizontal" 6 tools:context=".MainActivity" > 7 8 9 </LinearLayout>
2)fragment1视图
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:background="#ff0000" 6 android:orientation="vertical" > 7 8 9 </LinearLayout>
3)fragment2视图
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:background="#0000ff" 6 android:orientation="vertical" > 7 8 9 </LinearLayout>
2、java代码
1)切换代码
1 package com.example.myfragment; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.app.FragmentManager; 6 import android.app.FragmentTransaction; 7 import android.view.Menu; 8 9 public class MainActivity extends Activity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 16 //判断手机当前朝向 17 int width = getWindowManager().getDefaultDisplay().getWidth(); 18 int height = getWindowManager().getDefaultDisplay().getHeight(); 19 20 Fragment1 fragment1 = new Fragment1(); 21 Fragment2 fragment2 = new Fragment2(); 22 FragmentManager fm = getFragmentManager(); 23 FragmentTransaction ft = fm.beginTransaction(); 24 //R.id.content说明是当前的模板 25 if(width > height){ 26 //水平 27 ft.replace(android.R.id.content, fragment1); 28 }else{ 29 //垂直 30 ft.replace(android.R.id.content, fragment2); 31 } 32 33 ft.commit(); 34 } 35 36 37 38 39 }
2)fragment1和fragment2代码
1 package com.example.myfragment; 2 3 import android.app.Fragment; 4 import android.os.Bundle; 5 import android.view.LayoutInflater; 6 import android.view.View; 7 import android.view.ViewGroup; 8 9 public class Fragment2 extends Fragment { 10 11 @Override 12 public View onCreateView(LayoutInflater inflater, ViewGroup container, 13 Bundle savedInstanceState) { 14 // TODO Auto-generated method stub 15 return inflater.inflate(R.layout.fragment2, null); 16 } 17 18 }

浙公网安备 33010602011771号