我在viewpager中有两个标签。因此,在fragment1中,我输入了一个文本,然后在tab2中选择了该文本,然后fragment2将从fragment1中的文本中获取数据。

例如:当我打开tab1->输入文本是“ abcd”->我打开tab2->我想从tab1(fragment1)获得文本是“ abcd”。

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);

        Singleton singleton = Singleton.GetInstance();;
        singleton.SetSource("abcd");

    }

}public class Singleton
    {
        private static Singleton singleton;

        string a = null;
        private Singleton()
        {

        }

        public static Singleton GetInstance()
        {
            if (singleton == null)
                singleton = new Singleton();
            return singleton;
        }
        public void SetSource(string text)
        {
            this.a = text;
        }

        public string showMessage()
        {
            return a;
        }


    }




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();

    }
}


我已经尝试过了,但是没有结果。

最佳答案

经过数小时的研究/测试和调试并解决之后,请尝试一下。


在您的活动中


添加公共字符串tabFragment {get;组; }

在您的源代码片段中


即单击或导航到其他片段




string tab = ((ActivityUser)Activity).tabFragmentAddUser;
FragmentAddUser fragment = (FragmentAddUser);
Activity.SupportFragmentManager.FindFragmentByTag(tab);
fragment.setValText("Hello");
viewPager.SetCurrentItem(1, true);




在目标片段中(即将修改哪些元素)


添加这样的方法




  公共无效setValText(字符串str){txtUsrFirstName.Text = str; }


================================================== ================

关于c# - 如何在Xamarin Android上的标签之间传递数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38045610/

10-13 03:21