vendredi 1 juillet 2016

How to pass data between tabs on Xamarin Android?

I have two tabs in viewpager. So in fragment1 I input a text and when in tab2 is selected and then fragment2 will get data from that text from fragment1.

ex: when I open tab1-> I input a text is "abcd" -> I open tab2 -> I want to get a text is "abcd" from tab1(fragment1).

public class Fragment1 : Android.Support.V4.App.Fragment
    {
        Fragment2 frag2 = new Fragment2();
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            //return base.OnCreateView(inflater, container, savedInstanceState);
            return inflater.Inflate(Resource.Layout.view1, container, false);
            frag2.add("123456");
        }
    }

public class Fragment2 : Android.Support.V4.App.Fragment
	{
		public List<string> data = new List<string>();
		public void add(string t)
		{
			data.Add(t);
		}
		TextView txt;
		public override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Create your fragment here


		}

		public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			// Use this to return your custom view for this Fragment
			// return inflater.Inflate(Resource.Layout.YourFragment, container, false);

			//return base.OnCreateView(inflater, container, savedInstanceState);
			return inflater.Inflate(Resource.Layout.view2, container, false);
			txt = View.FindViewById<TextView>(Resource.Id.txtgetdata);
			if (data != null)
			{
				txt.Text = data[0];
			}
			else
				Toast.MakeText(Application.Context, "no", ToastLength.Long).Show();

		}
	}

.

I have tried it but don't having the result.

Aucun commentaire:

Enregistrer un commentaire