標籤:android 片段 使用者體驗 fragment 源碼
片段
片段可看作另外一種形式的活動,可以建立片段來包含視圖。
片段總是嵌入在活動中,一般有兩種常見形式:
1、片段A和片段B分別處於不同的活動中,當選擇片段A中的某一項時,觸發片段B啟動;
2、片段A和片段B處於同一個活動中,共用同一活動,以建立更佳的使用者體驗。
點此下載完整源碼~(代碼適用於本文章所講)
1、建立一個名為“Fragments”的項目,在res/layout檔案夾下,分別建立fragment1.xml、fragment2.xml;在當前包名下,分別建立Fragment1.java、Fragment2.java:
fragment1.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:background="#00FF00" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="This is fragment #1" android:textColor="#000000" android:textSize="25sp" /></LinearLayout>
fragment2.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:background="#FFFE00" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="This is fragment #2" android:textColor="#000000" android:textSize="25sp" /></LinearLayout>
Fragment1.java:
package net.zenail.fragments;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment1 extends Fragment {// 繼承Fragment基類// 繪製片段UI:使用一個LayoutInflauter對象來增大指定XML檔案中的UI。container參數引用父ViewGroup,準備用於嵌入片段的活動。// savedInstanceState參數允許將片段還原到前一次儲存的狀態。@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubreturn inflater.inflate(R.layout.fragment1, container, false);}}
Fragment2.java:
package net.zenail.fragments;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment2 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubreturn inflater.inflate(R.layout.fragment2, container, false);}}
2、在main.xml檔案中添加兩個片段:
<fragment android:id="@+id/fragment1" android:name="net.zenail.fragments.Fragment1" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="1" tools:layout="@layout/fragment1" /> <fragment android:id="@+id/fragment2" android:name="net.zenail.fragments.Fragment2" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="1" tools:layout="@layout/fragment2" />
3、運行,效果如下: