------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
1.静态的使用
1.1 在layout中添加frament1.xml和frament2.xml文件,之后在main.xml中添加frament标签name中指定相对应的java文件
<?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:orientation="horizontal" >
<fragment
android:id="@+id/fragment1"
android:name="com.shenjian.sensor.Flagment1"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
<fragment
android:id="@+id/fragment2"
android:name="com.shenjian.sensor.Flagment2"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
</LinearLayout>
1.2 新建Fragment1,Fragment1类 继承Fragment(import android.app.Fragment;最低版本3.0 要想在2.2以上使用要用import android.support.v4.app.FragmentTransaction;) ,实现onCreateView 方法
package com.shenjian.sensor;
import com.shenjian.paizhao.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Flagment1 extends Fragment {
/*
*当Fragement被创建的时候调用的方法,返回当前fragment显示的内容
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1, null);
}
}
2.动态的添加fragment(横屏显示蓝色 竖屏显示红色)
public class Main_activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//1.判断当前手机的朝向
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
Left_fragment left_fm= new Left_fragment();
right_fragment right_fm =new right_fragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (width>height) {
//先remove掉 在替换掉 参数:要替换的窗体 (android.R.id.content 当前窗体的id),fragment类
transaction.replace(android.R.id.content, left_fm);
} else {
transaction.replace(android.R.id.content, right_fm);
}
//关闭事务
transaction.commit();
}
}