Xamarin Fragment Flexible UI Android

In this tutorial you will learn how to build xamarin fragment flexible UI android.We will use Fragments and Frame Layout.You must read Fragment in Android and Frame Layout tutorial before starting this tutorial.You will create a layout with list which will be responsive for all android devices like smartphone,tablet etc.

For list you will use ListFragment.

Create new xamarin fragment flexible ui android application project.Go to your Main.axml File and add Fragment,Frame Layout.

xamarin fragment,xamarin fragment flexbile ui,xamarin fragment flexible ui android,fragment flexible ui android,

Don’t forget to add class within fragment.

MainActivity.cs Class

using Android.App;
using Android.OS;

namespace com.xamarin.sample.fragments.honeycomb
{
    [Activity(Label = "Fragments Walkthrough", MainLauncher = true, Icon = "@drawable/launcher")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.activity_main);
        }
    }
}

Next create new class Shakespeare.cs and put list items,content.
Shakespeare.cs

namespace com.xamarin.sample.fragments.honeycomb
{
	internal class Shakespeare
	{
		public static string[] Dialogue = { "So shaken as we are, so wan with care," +
			"Find we a time for frighted peace to pant," +
			"Whose soldier now, under whose blessed cross" +
			"Of you, my gentle cousin Westmoreland," +
			"What yesternight our council did decree" +
			"In forwarding this dear expedience.", "Hear him but reason in divinity," +
			"And never noted in him any study," + "Any retirement, any sequestration" +
			"From open haunts and popularity.", "I come no more to make you laugh: things now," +
			"Will leave us never an understanding friend." , "First, heaven be the record to my speech!" +
			"Thou art a traitor and a miscreant," + 
			"Too good to be so and too bad to live," + "Since the more fair and crystal is the sky," + 
			"The uglier seem the clouds that in it fly." + "Once more, the more to aggravate the note," +
			"With a foul traitor's name stuff I thy throat;" + "And wish, so please my sovereign, ere I move," + 
			"What my tongue speaks my right drawn sword may prove.", "Now is the winter of our discontent"+
			"Dive, thoughts, down to my soul: here" + "Clarence comes.", "To bait fish withal: if it will feed nothing else," +
			"bargains, cooled my friends, heated mine" + "enemies; and what's his reason? I am a Jew. Hath" + 
			"revenge? If we are like you in the rest, we will" + "resemble you in that. If a Jew wrong a Christian," + 
			"what is his humility? Revenge. If a Christian" + "wrong a Jew, what should his sufferance be by" +
			"Christian example? Why, revenge. The villany you" + "teach me, I will execute, and it shall go hard but I" + 
			"will better the instruction.", "Virtue! a fig! 'tis in ourselves that we are thus" + 
			"or thus. Our bodies are our gardens, to the which" + "our wills are gardeners: so that if we will plant" +
			"you call love to be a sect or scion.", "Blow, winds, and crack your cheeks! rage! blow!" +
			"Crack nature's moulds, an germens spill at once," + "That make ingrateful man!" };
		public static string[] Titles = { "Henry IV (1)",
			"Henry V",
			"Henry VIII",
			"Richard II",
			"Richard III", "Merchant of Venice",
			"Othello",
			"King Lear" };
	}
}

Create new Class for List Items.
TilesFragment.cs

using System;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;

namespace com.xamarin.sample.fragments.honeycomb
{
    public class TitlesFragment : ListFragment
    {
        private int _currentPlayId;
        private bool _isDualPane;

        public override void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);

            var detailsFrame = Activity.FindViewById(Resource.Id.details);
            _isDualPane = detailsFrame != null && detailsFrame.Visibility == ViewStates.Visible;

            var adapter = new ArrayAdapter(Activity, Android.Resource.Layout.SimpleListItemChecked, Shakespeare.Titles);
            ListAdapter = adapter;

            if (savedInstanceState != null)
            {
                _currentPlayId = savedInstanceState.GetInt("current_play_id", 0);
            }

            if (_isDualPane)
            {
                ListView.ChoiceMode = ChoiceMode.Single;
                ShowDetails(_currentPlayId);
            }
        }

        public override void OnListItemClick(ListView l, View v, int position, long id)
        {
            ShowDetails(position);
        }

        public override void OnSaveInstanceState(Bundle outState)
        {
            base.OnSaveInstanceState(outState);
            outState.PutInt("current_play_id", _currentPlayId);
        }

        private void ShowDetails(int playId)
        {
            _currentPlayId = playId;
            if (_isDualPane)
            {
                // We can display everything in-place with fragments.
                // Have the list highlight this item and show the data.
                ListView.SetItemChecked(playId, true);

                // Check what fragment is shown, replace if needed.
                var details = FragmentManager.FindFragmentById(Resource.Id.details) as DetailsFragment;
                if (details == null || details.ShownPlayId != playId)
                {
                    // Make new fragment to show this selection.
                    details = DetailsFragment.NewInstance(playId);

                    // Execute a transaction, replacing any existing
                    // fragment with this one inside the frame.
                    var ft = FragmentManager.BeginTransaction();
                    ft.Replace(Resource.Id.details, details);
                    ft.SetTransition(FragmentTransit.FragmentFade);
                    ft.Commit();
                }
            }
            else
            {
                // Otherwise we need to launch a new activity to display
                // the dialog fragment with selected text.
                var intent = new Intent();

                intent.SetClass(Activity, typeof(DetailsActivity));
                intent.PutExtra("current_play_id", playId);
                StartActivity(intent);
            }
        }
    }
}

Then create Fragment Class.

DetailsFragment.cs

using System;

using Android.App;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;

namespace com.xamarin.sample.fragments.honeycomb
{
    internal class DetailsFragment : Fragment
    {
        public int ShownPlayId { get { return Arguments.GetInt("current_play_id", 0); } }

        public static DetailsFragment NewInstance(int playId)
        {
            var detailsFrag = new DetailsFragment { Arguments = new Bundle() };
            detailsFrag.Arguments.PutInt("current_play_id", playId);
            return detailsFrag;
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            if (container == null)
            {
                // Currently in a layout without a container, so no reason to create our view.
                return null;
            }

            var scroller = new ScrollView(Activity);

            var text = new TextView(Activity);
            var padding = Convert.ToInt32(TypedValue.ApplyDimension(ComplexUnitType.Dip, 4, Activity.Resources.DisplayMetrics));
            text.SetPadding(padding, padding, padding, padding);
            text.TextSize = 24;
            text.Text = Shakespeare.Dialogue[ShownPlayId];

            scroller.AddView(text);

            return scroller;
        }
    }
}

At last create class for replacing fragment.

DetailsActivity.cs

using Android.App;
using Android.OS;

namespace com.xamarin.sample.fragments.honeycomb
{
    [Activity(Label = "Details Activity")]
    public class DetailsActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            var index = Intent.Extras.GetInt("current_play_id", 0);

            var details = DetailsFragment.NewInstance(index); // Details
            var fragmentTransaction = FragmentManager.BeginTransaction();
            fragmentTransaction.Add(Android.Resource.Id.Content, details);
            fragmentTransaction.Commit();
        }
    }
}

Now Run your xamarin fragment flexible UI android application project.

xamarin fragment,xamarin fragment flexbile ui,xamarin fragment flexible ui android,fragment flexible ui android,

that’s it for xamarin fragment flexible UI android tutorial.

Thanks.