xamarin學習筆記A07(安卓Fragment)

(每次學習一點xamarin就做個學習筆記視頻來加深記憶鞏固知識)
如有不正確的地方,請幫我指正。

Fragment簡介
Android程序運行在手機、平板和電視等各種設備中,各設備屏幕尺寸差距很大。不希望做幾套程序來適應不同尺寸的設備。Fragment的產生就是解決這種問題。
Fragment是一種可以嵌入在Activity中的UI片段。
Fragment是Android3.0開始引入的新API技術。在Fragment中嵌套Fragment的功能是在Android4.2系統中才開始支持的,如果要在4.2之前系統運行就要使用support-v4庫。

Fragment的生命週期
下面是一張官網圖:
這裏寫圖片描述
可以看到和activity的生命週期類似,多了幾個方法。
OnAttach()當片段和活動建立關聯時調用。
OnCreateView()當片段加截佈局時調用。
OnActivityCreated()當與片段相關聯的活動創建完畢後調用。
OnDestroyView()當與片段關聯的視圖被移除的時候調用。
OnDetach()當片段和活動解除關聯的時候調用。

實現一個下面的圖功能,左邊是圖書列表,右邊是圖書介紹。這個界面是針對平板電腦的。而在手機界面中只顯示左邊的這塊,通過點擊左邊書名再在另一個新界面顯示書的簡介。
這裏寫圖片描述
下面是一張項目文件部分截圖:
這裏寫圖片描述
可以看到有兩個Main佈局文件,一個是在默認layout目錄中,一個在layout-sw600dp中,當程序運行在大於寬度600dp屏幕上時,系統會自動使用layout-sw600dp的Main佈局, 寬度小於600dp則使用layout目錄中的Main佈局。(sw是Smallest-width的縮寫)

默認的layout目錄中的Main佈局文件代碼如下:

<?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/bookRecyclerFragment"
      android:name="A07.BookRecyclerFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>
</LinearLayout>

就只有一個fragment,即書名列表片段bookRecyclerFragment。

Layout-sw600目錄中的Main佈局文件代碼如下:

<?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/bookRecyclerFragment"
    android:name="A07.BookRecyclerFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"/>

  <FrameLayout
    android:id="@+id/bookDescriptionFrameLayout"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="3">

    <fragment
      android:id="@+id/bookDescriptionFragment"
      android:name="A07.BookDescriptionFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>
  </FrameLayout>
</LinearLayout>

這個佈局文件用於寬度大於600dp的設備上,所以可顯示兩個片段,左邊的書名列表片段bookRecyclerFragment和右邊的書簡介片段bookDescriptionFragment。

完整代碼和視頻在我上傳的CSDN資源中http://download.csdn.net/detail/junshangshui/9910017

發佈了74 篇原創文章 · 獲贊 50 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章