在实际开发中静态的fragment几乎用的很少,比如在某个场景下使用布局,随着条件的变化又显示另外一个布局,那么这时候把布局写死就不是很适合,所以得 动态创建fragment,
activity_main.xml文件:
<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:id="@+id/main_layout"
android:orientation="horizontal"
>
</LinearLayout>
MainActivity.java
public class MainActivity extends FragmentActivity {
private FragmentManager fm;
private FragmentTransaction ft;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
if (display.getWidth() > display.getHeight()) {
Fragment1 fragment1 = new Fragment1();
ft.replace(R.id.main_layout, fragment1).commit();
} else {
Fragment2 fragment2 = new Fragment2();
ft.replace(R.id.main_layout, fragment2).commit();
}
}
}
Fragment1.java
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.fragment1, container, false);
}
}
Fragment2.java
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, container, false);
}
}
Fragment1 对应的布局文件 fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#0000ff"
>
<TextView
android:id="@+id/f1_tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="这是fragment111111的内容"
/>
</RelativeLayout>
Fragment2.java对应的fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ffff"
>
<TextView
android:id="@+id/f2_tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="这是fragment22222222的内容"
/>
</RelativeLayout>
效果图:
当竖屏的时候
注:FragmentManager类是管理Fragment的,
Fragment添加 移除 替换,这就好像是数据库中的事物,对同一个 状态要么成功,要么失败,而fragment的管理也采用了这个办法,
开启一个事务,通过调用beginTransaction()方法得到FragmentTransaction开启事物,
向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例
提交事务,调用commit方法提交
一定要记得commit,就像我们使用SharedPreferences一样,不 commit数据就保存不到文件中