roy
roy

Reputation: 1

Create Fragment Dynamically Xamarin android

How to create Fragment Dynamically and show data in fragment when Main.axml called in OnCreate method in android Xamarin.

Please Help

Thanks in advance

Upvotes: 0

Views: 87

Answers (1)

Grace Feng
Grace Feng

Reputation: 16652

You can dynamically create a FrameLayout for your fragment. For example:

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

    // Create your application here
    SetContentView(Resource.Layout.Main);

    LinearLayout root = FindViewById<LinearLayout>(Resource.Id.rootlayout);

    FrameLayout frame = new FrameLayout(this);
    frame.Id = 10001000;
    frame.LayoutParameters = new ViewGroup.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
    root.AddView(frame);

    if (savedInstanceState == null)
    {
        Fragment fragment = new MyFragment();
        FragmentTransaction ft = FragmentManager.BeginTransaction();
        ft.Add(frame.Id, fragment).Commit();
    }
}

Of course we need also create our custom Fragment for example like this:

public class MyFragment : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Create your view and add your data here. Return this view.
        //For example:
        TextView tv = new EditText(this.Activity);
        tv.Text = "This is Fragment";
        return tv;
    }
}

Upvotes: 1

Related Questions