Fragment的使用,有兩種方式:靜態的使用和動態的使用Fragment
作爲初學者,我先從最簡單的方式開始,即如何在Xamarin.Android裏面靜態的使用Fragment
1 開始之初,先解答一下我們爲什麼要使用Fragment?
Android運行在各種各樣的設備上,除了手機,還有平板等設備,那麼不同的設備屏幕類型是有很大差異的,難道無法做到一個App可以同時適應手機和平板麼?這個時候Fragment就很好的解決了這個問題。
2 進入正題,看看如何使用Fragment
(1) 首先建立一個叫fragment1的axml佈局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px"
android:background="#434A5A">
<ImageButton
android:id="@+id/id_title_left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="3dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="看這裏,這裏!"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
(2) 新建一個命名爲Fragement的文件夾,新建一個命名爲FragmentTest1的類文件
public class FragmentTest1 : Fragment
{
private ImageButton mLeftMenu;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.fragment1, container, false);
mLeftMenu = (ImageButton) view.FindViewById(Resource.Id.id_title_left_btn);
mLeftMenu.Click += (object sender, EventArgs e) =>
{
Toast.MakeText(Activity, "我是一個圖片! ", ToastLength.Short).Show();
};
return view;
}
}
接下來,我們就可以在Main.axml裏面使用Fragement了
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<fragment
android:id="@+id/id_fragment_title"
android:name="_1111_Test.Fragement.FragmentTest1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
把Fragment當成普通的View一樣聲明在Activity的佈局文件中,然後所有控件的事件處理等代碼都由各自的Fragment去處理~~代碼的可讀性、複用性以及可維護性瞬間提升了
運行結果: