星期六, 7月 02, 2016

[X.Andriod] 動態產生 Fragment

閱讀官方文章 Create a Fragment 後的練習筆記

[X.Andriod] 動態產生 Fragment-1

DynamicLayout.axml:只有一個 Button

[X.Andriod] 動態產生 Fragment-2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearDynamic"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="動態載入"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnDynamic" />
</LinearLayout>
DynamicFragmentLayout.axml:只有一個 TextView

[X.Andriod] 動態產生 Fragment-3
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView
        android:text="Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtDynamicCount"
        android:textSize="20dp" />
</LinearLayout>
DynamicActivity.cs
namespace FragmentsBase
{
    [Activity(Label = "FragmentsBase", MainLauncher = true, Icon = "@drawable/icon")]
    public class DynamicActivity : Activity
    {
        private int count = 0;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.DynamicLayout);

            FindViewById<Button>(Resource.Id.btnDynamic).Click += (sender, e) =>
            {
                DynamicFragment dynamic = new DynamicFragment();
                dynamic.DynamicName = $"動態產生 Fragment - {count}";
                count++;

                FragmentManager
                    .BeginTransaction()
                    .Add(Resource.Id.linearDynamic, dynamic)
                    .Commit();
            };
        }
    }
}
DynamicFragment.cs
namespace FragmentsBase
{
    public class DynamicFragment : Fragment
    {
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public string DynamicName { get; set; }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View v = inflater.Inflate(Resource.Layout.DynamicFragmentLayout, null);
            v.FindViewById<TextView>(Resource.Id.txtDynamicCount).Text = this.DynamicName;
            return v;
        }
    }
}
[X.Andriod] 動態產生 Fragment-4

沒有留言:

張貼留言