在片段之间传递字符串[]。怎么做?

时间:2016-04-21 05:56:41

标签: xamarin xamarin.android

片段1:

lst.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs e) {

				var intent = new Intent (this, typeof(TracksByGenres));
				intent.PutStringArrayListExtra ("keys",	items);
				StartActivity (intent);
			};
		

TracksByGenres是fragment2

  

错误:最佳重载方法匹配   `Android.Content.Intent.Intent(Android.Content.Context,System.Type)'   新意图有一些无效的参数(这个,   typeof运算(TracksByGenres));

Fragment2:

public async override void OnActivityCreated(Bundle savedInstancesState)
		{
			base.OnActivityCreated (savedInstancesState);
			paramKey = Intent.Extras.GetStringArray ("keys").ToString();

			lst = View.FindViewById<ListView> (Resource.Id.lstHome);

			

哪里不对?

1 个答案:

答案 0 :(得分:0)

var intent = new Intent (this, typeof(TracksByGenres));
            intent.PutStringArrayListExtra ("keys", items);
            StartActivity (intent);

上面的代码段是创建一个新Activity的实例并启动它。第二个参数typeof(TracksByGenres)实际应该是typeof(A class inheriting from Actiivty (not fragment))这会导致异常。

要切换片段,您需要使用FragmentTransaction。这是一个关于here的教程。

编辑:将数据传递给片段的示例,在评论中提问

public class TracksByGenres :Fragment
{
  string mData;
  public void AddData(string data)
  {
     mData=data;
  }
  public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
      // inflate layout and store in variable
       //you can use data here
       // myTextView.Text=mData;
   }
}

然后在活动中,

创建第一个片段,在FrameLayout中添加数据和加载

FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
TracksByGenres fragment = new TracksByGenres();

fragment.AddData("Xamarin is awesome");
// The fragment will have the ID of Resource.Id.fragment_container.
fragmentTx.Add(Resource.Id.fragment_container, fragment);

// Commit the transaction.
fragmentTx.Commit();

用新片段替换片段,添加数据。在这个例子中,我使用相同的片段以方便。

TracksByGenres aDifferentDetailsFrag = new TracksByGenres();

aDifferentDetailsFrag.AddData("Xamarin is awesome");

// Replace the fragment that is in the View fragment_container (if applicable).
fragmentTx.Replace(Resource.Id.fragment_container, aDifferentDetailsFrag);

// Add the transaction to the back stack.
fragmentTx.AddToBackStack(null);

//提交交易。     fragmentTx.Commit();