将自定义对象传递给 Xamarin Android 中的下一个活动 [英] Pass custom objects to next activity in Xamarin Android

查看:21
本文介绍了将自定义对象传递给 Xamarin Android 中的下一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些自定义对象,例如 RootObjectForm,我想将它们传递给下一个活动.

I've got a few custom objects like RootObject and Form that I want to pass on to the next activity.

这是一个RootObject的例子:

public class RootObject
{
    public Form Form { get; set; }
}

但是如何将 RootObject 传递给带有 Intent 的下一个 Activity 并在下一个 Activity 中获取它?在 Form 中,还有多个带有 Lists 和东西的属性,我需要在下一个 Activity 中访问一些属性.我的意图是这样调用的:

But how can I pass RootObject to the next activity with an Intent and get it in the next Activity? In Form there are again multiple properties with Lists and stuff and I need to access some of the properties in my next Activity. My intent is called like this:

saveButton.Click += delegate {
    if(ValidateScreen()){
        SaveData();
        Intent intent = new Intent(this, typeof(MainActivity));
        Bundle b = new Bundle();
        b.PutSerializable("RootObject", RootObject);
        StartActivity(intent);
    }
};

推荐答案

我知道这是一个老问题,但我认为我的回答可能对某人有所帮助.我所做的是使用 JSON.Net 包,您可以使用 Nuget Manager 安装该包.通过使用 JSON,您可以在第一个活动中序列化您的对象,然后在第二个活动中反序列化.我就是这样做的:

I know this is an old question but I think my answer might help someone. What I did is that I used JSON.Net package that you can install with Nuget Manager. By using JSON you can serialize your object in first activity and then deserialize in the second activity. This is how I did it:

活动 1

using Newtonsoft.Json;
...
void mBtnSignIn_Click(object sender,EventArgs e)
{
      User user = new User();
      user.Name = "John";
      user.Password = "password";

      Intent intent = new Intent(this,typeof(Activity2));
      intent.PutExtra("User",JsonConvert.SerializeObject(user));
      this.StartActivity(intent);
      this.Finish();

}

活动 2

using Newtonsoft.Json;
...
private User user;
protected override void OnCreate(Bundle savedInstanceState)
{
      base.OnCreate(savedInstanceState);

      SetContentView(Resource.Layout.Activity2);
      user = JsonConvert.DeserializeObject<User>(Intent.GetStringExtra("User"));
}

希望这对某人有所帮助.

Hope this would help someone.

这篇关于将自定义对象传递给 Xamarin Android 中的下一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆