安卓第十天筆記-fragment,安卓-fragment
安卓第十天筆記-fragmentFragment(片段)一.Fragment簡介
*Fragment是3.0引入的API,主要為瞭解決平板,大螢幕手機顯示問題
*Fragment代表了Activity的子模組,因此可以把fragment理解成Activity的片段
*Fragment必須被嵌入Activity中使用
二.建立Fragment的步驟三使用fragment使用Activity
*建立一個布局用來填充fragment
<?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="vertical"><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="聲音大小"/><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="速度"/><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="3D"/><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="左聲道"/><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="右聲道"/></LinearLayout>
*建立一個fragement public class SoundFragment extends Fragment {
@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.sound_item,null) ; return view;}
*主介面布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layoutwidth="matchparent" android:layoutheight="matchparent" android:orientation="vertical"><!--容器--><FrameLayoutandroid:id="@+id/fl_container"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="3"></FrameLayout><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:onClick="sound" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="聲音"/></LinearLayout></LinearLayout>
*Activity
/** * 點擊聲音按鍵顯示fragment * @param v */ public void sound(View v){ //聲明Fragment SoundFragment soundFragment = new SoundFragment(); //擷取Fragment管理器 FragmentManager manager = getFragmentManager(); //開啟事務 FragmentTransaction transaction = manager.beginTransaction(); //替換掉當前布局中的幀版面配置容器 transaction.replace(R.id.fl_container,soundFragment); //提交事務 transaction.commit();}
四生命週期
- onAttach---用於與Acivity建立串連與斷開,當該Fragment被添加到Activity時被回調,只會被調用一次
- onCreate---建立Fragment時被調用
- onCreateView--每次建立Fragment時都會被調用
- onActivityCreated:當Fragment所在的Activity被啟動完成後調用
- onStart:啟動Fragment時調用
- onResume:恢複Fragment時被回調,在onStart方法後一定會被調用
- onPause:暫停Fragment時被回調
- onStop:停止Fragment時被回調
- onDestroyView:建立與銷毀視圖
- onDesctory:用於初始化與銷毀與Activity中的一樣
- onDetach:將這個Fragment從Activity中刪除,替換完成時調用這個方法,在onDestroy方法後一定回調用這個方法
五 Activity與Fragment生命週期對比
Activity--------------------Fragment onAttach() onCreate() onCreateView()onCreate() onActivityCreatedonStart() onStart()onResume() onResume()onPause() onPause()onStop() onStop() onDestoryView() onDestory()onDestory() onDetach()