標籤:net type horizon 生命週期 繼承 enter back this wrap
Fragment是片段的意思,能夠參照Activity來理解Fragment,由於它們都能包括布局,都有自己的生命週期。
以下我們要讓主活動包括兩個片段,而且讓兩個片段充滿螢幕
1.首先,建立兩個片段的布局檔案
left.xml
<?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" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Button" /></LinearLayout>
right.xml
<?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:background="#00ff00" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="20sp" android:text="right"/></LinearLayout>
2.接著,建立一個 LeftFragment 類和RightFragment類,繼承自 Fragment。
public class LeftFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.left, container,false); return view; }}
public class RightFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.right, container,false); return view; }}
3.最後。改動 activity_main.xml中的代碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <fragment android:id="@+id/left_fragment" android:name="com.example.fragment.LeftFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/right_fragment" android:name="com.example.fragment.RightFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /></LinearLayout>
4.效果例如以所看到的
5.注意事項:
當時建立 LeftFragment 類和RightFragment類的時候沒有把傳回值改動為return view;
android:name=”com.example.fragment.LeftFragment”不能寫錯
Android筆記(十一)第一個Fragment