在手機中設計,我們可以將新聞標題列表放在一個 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