我在viewpager中有两个标签。所以在fragment1中我输入了一个文本,当选择tab2时,然后fragment2将从fragment1中获取该文本的数据。
例如:当我打开tab1时 - >我输入的文字是" abcd" - >我打开tab2 - >我想得到一个文字是" abcd"来自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);
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();
}
}
我已经尝试过,但没有结果。
答案 0 :(得分:1)
经过几个小时的研究/测试&amp;调试并解决,试试这个。
在您的活动中
在源代码片段中
string tab = ((ActivityUser)Activity).tabFragmentAddUser; FragmentAddUser fragment = (FragmentAddUser); Activity.SupportFragmentManager.FindFragmentByTag(tab); fragment.setValText("Hello"); viewPager.SetCurrentItem(1, true);
public void setValText(string str){txtUsrFirstName.Text = str; }
=============================================== ===================
答案 1 :(得分:0)
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.SetArguments(bundle);
在创建另一个片段
Bundle bundle = this.GetArguments();
int myInt = bundle.GetInt(key, defaultValue);
可选地,两个片段不应该直接通信,而应该通过活动进行通信
来自开发者网站:
通常你会想要一个片段与另一个片段进行通信 示例根据用户事件更改内容。所有 片段到片段的通信是通过相关联的 活动。两个碎片永远不应该直接沟通。