第四周

在手機中設計,我們可以將新聞標題列表放在一個 Activity 中,將新聞的詳細內容放在另一個 Activity 中。

碎片的使用方式

1、新建一個FragmentTest 項目

在一個活動當中添加兩個碎片,并讓這兩個碎片平分活動空間。

新建一個左側碎片布局left_fragment.xml,代碼如下所示:

[html]view plaincopy

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:text="Button"

/>

這個布局非常簡單,只放置了一個按鈕,并讓它水平居中顯示。

2、新建右側碎片布局right_fragment.xml

[html]view plaincopy

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#00ff00"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:textSize="20sp"

android:text="This is right fragment"

/>

我們將這個布局的背景色設置成綠色,并放置了一個TextView 用于顯示一段文本。

3、新建一個LeftFragment 類,繼承自Fragment

注意,這里可能會有兩個不同包下的Fragment 供你選擇,

建議使用Android.app.Fragment,因為我們的程序是面向Android 4.0以上系統的,

另一個包下的Fragment 主要是用于兼容低版本的Android 系統。

LeftFragment的代碼如下所示:

[java]view plaincopy

publicclassLeftFragmentextendsFragment

{

@Override

publicView onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)

{

View view = inflater.inflate(R.layout.left_fragment, container,false);

returnview;

}

}

這里僅僅是重寫了Fragment 的onCreateView()方法,

然后在這個方法中通過LayoutInflater的inflate()方法將剛才定義的left_fragment 布局動態加載進來,

整個方法簡單明了。

4、用同樣的方法再新建一個RightFragment

[java]view plaincopy

publicclassRightFragmentextendsFragment

{

@Override

publicView onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)

{

View view = inflater.inflate(R.layout.right_fragment, c

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 用戶開發中的布局開發 布局和控件(完成UI設計) 涉及布局layout和控件View 線性布局和相對布局 顯示文本...
    董朕閱讀 217評論 0 0
  • 碎片是什么 碎片 (Fragment) 是一種可以嵌入在 Activity 當中的 UI 片段,它能讓程序更加合理...
    墨櫛楓閱讀 1,112評論 0 1
  • 動態創建fragment的流程 1.0 新建一個類繼承fragment. 2.0 在自定義的fragment里面復...
    左神話閱讀 2,236評論 0 3
  • 我是一個聊到感情就會泄氣的人,看到周邊的親朋好友的婚姻狀態,我就會感慨一個人過得真爽。有一天,和好友聊到感情問題,...
    Roughlay成長日記閱讀 302評論 0 0
  • 十一假期已經悄然過去許多天,可是自己卻并沒有收獲到預期的,在自責的同時,也有一些話要對自己說。事情的起源還是要從假...
    木魚的城堡閱讀 419評論 0 1