简体   繁体   English

在 Xamarin 中的活动之间传递数据

[英]Passing data between activities in Xamarin

I can't share the data I have in MainActivity to the Welcome activity, even though I followed the instructions of this page: https://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/我无法将 MainActivity 中的数据共享到 Welcome 活动,即使我遵循了此页面的说明: https : //developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/

MainActivity (Activity1)主活动(Activity1)

Button button = FindViewById<Button>(Resource.Id.send);
EditText myName = FindViewById<EditText>(Resource.Id.name);
string name = myName.Text;

button.Click += delegate { 
    var welcome = new Intent(this, typeof(Welcome));
    welcome.PutExtra("name", name);
    StartActivity(welcome);
};

Welcome (Activity2)欢迎(活动2)

string name = Intent.GetStringExtra("name") ?? "Data not available";

I get null, don't know why.我得到空值,不知道为什么。 Any suggestions or advise?有什么建议或建议吗?

You have to fetch the text when the button is clicked otherwise it will have no value( because when the UI is created, EditText would be empty hence null value at that time ) so您必须在单击按钮时获取文本,否则它将没有值(因为创建 UI 时,EditText 将为空,因此当时为空值)所以

string name = null;
button.Click += delegate { 
        name = myName.Text;
        var welcome = new Intent(this, typeof(Welcome));
        welcome.PutExtra("name", name);
        StartActivity(welcome);
    };

If you are going to a child view, use StartActivityForResult if you want to give back the result.如果您要去子视图,如果您想返回结果,请使用 StartActivityForResult。 You can get return objects in the ActivityResult:您可以在 ActivityResult 中获取返回对象:

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)

So this is a good way for passing data and returning data between activities.所以这是在活动之间传递数据和返回数据的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM