如何在Xamarin中的片段之间传递数据?

时间:2017-08-21 20:31:44

标签: android android-fragments xamarin xamarin.android

我想在两个片段之间传递数据。我该怎么办?

此代码给出了一个错误:

片段1:

myips = myip.Text;
mytracks = int.Parse(mytrack.Text);

intent = new Intent(this.Activity, typeof(TabFragment2));

intent.PutExtra("MyData", myip.Text);
intent.PutExtra("MyData1", mytrack.Text);

片段2:

string myips = Activity.Intent.GetStringExtra("MyData");
int mytracks = int.Parse(Activity.Intent.GetStringExtra("MyData1"));

1 个答案:

答案 0 :(得分:2)

  

intent = new Intent(this.Activity,typeof(TabFragment2));

Fragment是应用程序的用户界面或行为的一部分可以放在活动中,您不应该使用此方法打开Fragment

像这样打开你的TabFragment2

var fragment = new TabFragment2();
// Execute a transaction, replacing any existing fragment with this one inside the frame.
var fragmentTransaction = FragmentManager.BeginTransaction();
fragmentTransaction.Replace(Resource.Id.fragment, fragment );
fragmentTransaction.Commit();

有关信息,您可以阅读document,此处是example;

  

我想在两个片段之间传递数据。

当您使用fragmentTransaction.Replace方法打开TabFragment2时,您可以传递以下数据:

当您打开Fragment2时:

Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.PutString("param", myip.Text);
args.PutInt("paramInt", 12);
fragment.Arguments = args;

Fragment2 中,从Arguments获取数据:

 public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
 {
      View view = LayoutInflater.From(Activity).Inflate(Resource.Layout.fragment2, null);
      if (Arguments != null)
        {
            String mParam1 = Arguments.GetString("param");    
            int mParam2 = Arguments.GetInt("paramInt");
        }
  }