Fragment
是Android3.0后引入的一个新的API,为了适应大屏幕的平板电脑。使用Fragment
可以把屏幕划分成几块,然后进行分组,进行一个模块化的管理。
Fragment
相对于Activity
多了onAttach(Context)
和onDetach()
,用于加载和释放资源。
静态加载
在布局文件中直接加载自定义fragment
。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/fragment_left" android:name="com.blog.demo.component.fragment.FragmentLeft" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" /> </LinearLayout>
FragmentLeft
继承Fragment
,在onCreateView()
方法中定义界面。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="fragment left"/> </LinearLayout>
动态加载
假如在横屏情况下,我们可以加载不同布局文件。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/fragment_left" android:name="com.blog.demo.component.fragment.FragmentLeft" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/> <FrameLayout android:id="@+id/fragment_right" android:layout_width="0dp" android:layout_weight="2" android:layout_height="match_parent" /> </LinearLayout>
使用FragmentManager
对Fragment
进行动态的加载。
if (findViewById(R.id.fragment_right) != null) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.add(R.id.fragment_right, new FragmentRight()); ft.commitAllowingStateLoss(); }
联系客服