简体   繁体   中英

Can an activity default constructor be overloaded with monodroid?

In standard C#, I can overload the default constructor with something like

public class foo
{
  data bar;
  public foo(data bar)
  {
     this.bar = bar;
  }
}

Is there a way I can do this in monodroid? I'm trying to overload a default constructor in an activity (just to make it fun!).

Can you provide an Activity constructor which takes parameters? Yes. Would it be at all helpful? No, because Activities are started through Context.StartActivity() , which provides no mechanism to invoke a non-default constructor.

The "Android Way" to transfer data between Activities is to use the Intent "extras" mechanism, eg Intent.PutExtra(string,string) and Intent.GetStringExtra(string) , which introduces it's own set of problems:

  1. Intents are also an IPC mechanism (as an Activity may actually reside in another process -- this is by design), so you're restricted to types which can be marshaled across process boundaries.
  2. String s, int s, and other builtin types are supported, but aren't exactly "high level" objects.
  3. "Higher level" objects are supported through the android.os.Parcelable interface, but (a) has a "marshal by value" semantic, so isn't useful for sharing read+write data between activities, and (b) Mono for Android doesn't currently support implementing this interface .

So how do you share data between Activities? By punting.

  • Place the data onto an Application subclass. This will be accessible via the Context.ApplicationContext property, and can store process-global state.
  • Use some other public static field within your process to contain the shared information.
  • Provide a ContentProvider implementation which will store and provide the desired data when prompted.
  • Sqlite?
  • etc.

You don't implement constructors in activities in Android. Please perform this sort of initialization in onCreate() , after calling super.onCreate() .

(my apologies for the Java syntax -- I don't speak C#)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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