fragment的切换

时间:2023-03-09 01:46:08
fragment的切换

1、视图

1)主视图

 <LinearLayout 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:orientation="horizontal"
tools:context=".MainActivity" > </LinearLayout>

2)fragment1视图

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"
android:orientation="vertical" > </LinearLayout>

3)fragment2视图

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
android:orientation="vertical" > </LinearLayout>

2、java代码

1)切换代码

 package com.example.myfragment;

 import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //判断手机当前朝向
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight(); Fragment1 fragment1 = new Fragment1();
Fragment2 fragment2 = new Fragment2();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//R.id.content说明是当前的模板
if(width > height){
//水平
ft.replace(android.R.id.content, fragment1);
}else{
//垂直
ft.replace(android.R.id.content, fragment2);
} ft.commit();
} }

2)fragment1和fragment2代码

 package com.example.myfragment;

 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.fragment2, null);
} }