摘要:[Basic Andriod 讀書會] 2.3 Fragment
可以把Fragment想成是另一種型式的Activty,他也有自己的layout xml ,他必需嵌在Activity內。(先想成是web的 frame)
動態加入Fragment可以讓介面更有彈性,例如在Smartphone上執行,只載入一個fragment,若在tablet上執行,就可載入較多fragment。
下面是一個MainActivity內有兩個Fragment的layout xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”horizontal” >
<fragment
android:name=”tw.example.com.Fragment1”
android:id=”@+id/fragment1”
android:layout_weight=”1”
android:layout_width=”0px”
android:layout_height=”match_parent” />
<fragment
android:name=”tw.example.com.Fragment2”
android:id=”@+id/fragment2”
android:layout_weight=”1”
android:layout_width=”0px”
android:layout_height=”match_parent” />
</LinearLayout>
另外,必需要注意的是Fragment是繼承Fragment,DialogFragment, ListFragment, PreferenceFragment類別,Activity是繼承Activity類別
在onCreate這邊有些不同
Activity的onCreate:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
}
Fragment的onCreate:
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//---Inflate the layout for this fragment---
return inflater.inflate(
R.layout.fragment1, container, false);
}
其中,inflater指定layout,container 設定嵌入的Activity,savedInstanceState儲存在restore fragment的一些狀態。