Reputation: 27
i'm new to xamarin android. i want to send data from fragment to MainActivity. i searched google a lot almost all of them was in Java.
Upvotes: 1
Views: 1067
Reputation: 2119
You can do that by using Delegates:
Define delegates in your Fragment class
namespace Awesome.Android {
public class AwesomeFragment : Fragment {
public delegate void OnAwesomePress (int number);
public event OnAwesomePress sendOnAwesomePressEvent;
}
}
You can assign it when you create a Framgent
AwesomeFragment fragment = new AwesomeFragment ();
fragment.OnAwesomePress += OnAwesomePress;
After that, you implement OnAwesomePress
in your activity
private void OnAwesomePress (int number) {
}
Now, when you call sendOnAwesomePressEvent
in your Fragment, that event will be passed to Activity.
sendOnAwesomePressEvent (10);
Upvotes: 1
Reputation: 2034
You have few options:
Access the parent activity.
Create a function called SetData(data) in your activity class.
Your fragmnet have the "Activity" property, so cast to your activity type and then call the setData function with your data.
((ParentActivity)this.Activity).SetData(data);
Use the SharedPreferences
Set (in fragment):
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", "some_data");
editor.Apply();
Get (in activity):
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (context);
String myData = prefs.GetString ("my_data", "");
Upvotes: 1