1

A typical pattern in Android/Java development is to have a nested class that access methods from the parent class:

public class MainActivity extends FragmentActivity {

  // implementation

  public class SectionsPagerAdapter extends FragmentPagerAdapter {
    String someString = getString(R.string.thestring);
  }
}

So in this case, the Context.getString() would be accessing the MainActivity context.
How would this convert to Xamarin.Android (Mono for Android)?
When trying the exact same pattern I get:

Error CS0038: Cannot access a nonstatic member of outer type Test.MainActivity' via nested type Test.MainActivity.SectionsPagerAdapter' (CS0038)

I could of course pass around a Context object, but that seems tedious to do.

4
  • I always extract nested class out and pass Activity in a constructor. Commented Mar 8, 2013 at 23:20
  • 1
    Also, could take a look at section 4.5 of docs.xamarin.com/guides/android/advanced_topics/api_design. Commented Mar 8, 2013 at 23:36
  • Hmm... that explains it. Write that down as an answer, and I'll accept it Commented Mar 9, 2013 at 0:10
  • Thanks. Could you do me a favor? Could you suggest tag xamarin.android is a synonym of monodroid? I can't do it because I am under 2.5k reputation. :( Commented Mar 9, 2013 at 0:21

2 Answers 2

3

According to API design document of Xamarin.Android:

Non-static nested classes, also called inner classes, are significantly different. They contain an implicit reference to an instance of their enclosing type and cannot contain static members (among other differences outside the scope of this overview).

So, you should pass a reference of MainActivity to SectionsPagerAdapter. Then, you could access members of MainActivity.

Sign up to request clarification or add additional context in comments.

1 Comment

could you write an example please?
2

Here an example. I hope it helps.

public class YourParentClassActivity : Activity
{
//your stuff 
//...


//The Nested Class (that can implement any interface or base class)
    class YourNextedExampleClass : WebViewClient
    {
        //Parent Class Reference
        private YourParentClassActivity _pc;
        public YourNextedExampleClass(YourParentClassActivity pc)
        {
            _pc = pc;
        }

        public override void OnReceivedSslError(WebView view, SslErrorHandler handler, SslError SSLError)
        {
            Intent i = new Intent(Intent.ActionView, Android.Net.Uri.Parse("xxx");
            _pc.StartActivity(i);
            _pc.Finish();
            handler.Proceed(); // Ignore SSL certificate errors
        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.